vue 父子组件通信

父组件 ------------------------------------------------------

<template>

    <div class="home">

        <img alt="Vue logo" src="../assets/logo.png">

        <!--  :fatherMsg  在子组件标签上通过 :属性名 传递给子组件 -->

        <!-- @toFatherManyArgs/@toFatherOneArg 是子组件 $emit传过来的第一个参数 -->

        <!-- 当只有一个参数时, 接收参数的关键词是: $event -->

        <!-- 当有多个参数时, 接收参数的关键词是: arguments -->

        <ChildComponent :fatherMsg='toChild' 

                   @toFatherManyArgs="toFatherManyArgs(arguments)"

                   @toFatherOneArg="toFatherOneArg($event)">

        </ChildComponent>


        {{receiveChild1}} {{receiveChild2}} {{receiveChild3}}

    </div>

</template>

<script>

import ChildComponent from '../components/Child.vue'

export default {

    name: 'HomeView',

    data() {

        return {

            toChild: "world !",

            receiveChild1: "",

            receiveChild2: "",

            receiveChild3: "",

        }

    },

    components: {

        ChildComponent

    },

    methods: {

        toFatherManyArgs(args) {

            this.receiveChild1 = args[0];

            this.receiveChild2 = args[1];

        },

        toFatherOneArg(arg) {

            this.receiveChild3 = arg;

        }

    }

}

</script>


子组件 ------------------------------------------------------

<template>

    <div id="child-box">

        {{message}}

        {{fatherMsg}}

    </div>

</template>

<script>

export default {

    name: 'ChildView',

    // 通过 props 接收父组件传过来的字段

    props: ["fatherMsg"],

    data() {

        return {

            message: 'hello',

            say: 'nice to meet you',

        }

    },

    created() {

        this.$emit('toFatherManyArgs', this.say, "kangkang")

        this.$emit('toFatherOneArg', "meimei")

    },

}

</script>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件是 vue.js 最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互引用。...
    風語者Alex阅读 274评论 0 0
  • 父亲<template>//chriden对应儿子的文件名字 oldInfo对应你需要传给子组件的数据 cl...
    heler阅读 331评论 0 1
  • 一 父组件向子组件通过props传递数据 在组件中,使用选项props来声明需要从父级接收到的数据。props的值...
    名字是乱打的阅读 213评论 0 1
  • 1.子组件的 props 属性通过子组件的 props 属性,可以将父组件上的数据传入子组件,如下例中的 deli...
    极客传阅读 149评论 0 0
  • vue设计模式是数据流在组件之间是单向流动,组件内部是数据双向绑定, 父组件一般会通过props绑定数据传递给子组...
    杰出噜阅读 266评论 0 0