vue 父子组件通讯props/emit

   props

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

父组件:css

<parent>
    <child :childMsg="msg"></child>//这里必需要用 - 代替驼峰
</parent>

data(){
    return {
        msg: [1,2,3]
    };
}

子组件经过props来接收数据: 
方式1:vue

props: ['childMsg']

方式2 :this

props: { childMsg: Array //这样能够指定传入的类型,若是类型不对,会警告 }

方式3:spa

props: {
    childMsg: {
        type: Array, default: [0,0,0] //这样能够指定默认的值 } }

2.子组件与父组件通讯

若子组件想要改变数据?code

这在vue中是不容许的,由于vue只容许单向数据传递,咱们能够经过触发事件来通知父组件改变数据,从而达到改变子组件数据的目的.blog

子组件:事件

<template>
    <div @click="up"></div>
</template>

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

父组件:string

<div>
    <child @up="change" :msg="msg"></child> //监听子组件触发的upup事件,而后调用change方法
</div>
methods: { change(msg) { this.msg = msg; } }
相关文章
相关标签/搜索