标签:通信 组件 改变 自定义事件 属性 警告 hang 赋值 mit
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] //这样可以指定默认的值 } }
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
标签:通信 组件 改变 自定义事件 属性 警告 hang 赋值 mit
原文地址:http://www.cnblogs.com/136asdxxl/p/7152844.html