vue父子组件通信

// 1:父组件传值给子组件

// 父组件:
<parent>
    <child :child-msg="msg"></child>  //这里必须要用 - 代替驼峰
</parent>

data(){
    return {
        msg: [1,2,3]
    };
}
// 子组件通过props来接收数据: 
方式1:
props: ['childMsg']

方式2 :
props: {
    childMsg: Array //这样可以指定传入的类型,如果类型不对,会警告
}

方式3:
props: {
    childMsg: {
        type: Array,    //传入的类型
        default: [0,0,0] //这样可以指定默认的值
    }
}

//2:子组件与父组件通信

// 子组件:
<template>
    <div @click="testClick"></div>
</template>

methods: {
    testClick() {
        this.$emit('test','123'); //$emit(even,value)even 
     //是一个函数,value 是传给父组件的值,触发名为test方法, '123'为向父组件传递的数据 } }

// 父组件接收:  

<div>
    <child @test="change" :msg="msg"></child>  //监听子组件触发的test事件,然后调用change方法
</div>
methods: {
    change(val) {
        this.msg = val;  // val: 123
    }
}
// 3:父组件向子组件传字符串的特殊情况

<div>
  <child value="str"></child>
</div>
//
该种方法“只能传递字符串”,将child的data中的value = "str";不需要父组件data中有数据

Vue.component("child", {
  props:["value"],
  template: '<span>{{ value }}</span>'
});



 
posted @ 2018-08-29 16:50  cecelingmeng  阅读(79)  评论(0编辑  收藏  举报