码迷,mamicode.com
首页 > 其他好文 > 详细

vue2.0 父子组件 通信

时间:2017-07-12 01:23:08      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:通信   组件   改变   自定义事件   属性   警告   hang   赋值   mit   

一、父组件传递数据给子组件 (  parent  ==》 children  )

props 属性

》parent 组件 parent.vue

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

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

》child 组件 child.vue

写法一
props: [childMsg] // 驼峰式

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

写法三
props: {
    childMsg: {
        type: Array,        // 类型
        default: [0,0,0]   //这样可以指定默认的值
    }
}

 二、子组件传递数据给父组件 (  children  ==》 parent  )

vue是单向数据传递,子组件想要改变数据,需通过触发自定义事件来通知父组件改变数据,从而达到改变子组件数据的目的.

》child 组件  child.vue

<template>
    <button @click="sendToParent">点击按钮</button>
</template>

methods: {
    sendToParent() {
        this.$emit(childGet,父组件获取到子组件传递的数据); //主动触发
    }
}

》parent 组件 parent.vue

<div>
    <child @childGet="change" :msg="msg"></child> //监听子组件触发的childGet事件,然后调用change方法
</div>
methods: {
    change(msg) {  //参数msg是子组件传递的值
        this.msg = msg;  // 赋值给绑定的msg 属性
    }
}

子组件与子组件之间通信 若项目逻辑较复杂,建议使用 vuex 

vuex 介绍和具体使用见 官方文档 https://vuex.vuejs.org/

具体见demo   https://github.com/136shine/study_demo/tree/master/vue-demo1

vue2.0 父子组件 通信

标签:通信   组件   改变   自定义事件   属性   警告   hang   赋值   mit   

原文地址:http://www.cnblogs.com/136asdxxl/p/7152844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!