vue组件通信---props

   props 1.父组件传递数据给子组件 父组件:

 <parent>
    <child :childMsg="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.子组件与父组件通信 若子组件想要改变数据?
这在vue中是不允许的,因为vue只允许单向数据传递,我们可以通过触发事件来通知父组件改变数据,从而达到改变子组件数据的目的.

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

methods: {
    up() {
        this.$emit('up','hello'); //主动触发up方法,'hello'为向父组件传递的数据
    }
}

父组件:

 <div>
    <child @up="change" :msg="msg"></child> //监听子组件触发的upup事件,然后调用change方法
</div> 

methods: {
    change(msg) {
        this.msg = msg;
    }
}

转载于猿2048:➫《vue组件通信---props》

评论

暂无评论