- 父组件 --> 子组件
(1) props:父组件可以使用props向子组件传递数据
父组件:
<template>
<child :msg="message"></child>
</template>
<script>
import child from './child.vue';
export default {
components: {
child
},
data () {
return {
message: 'father message';
}
}
}
</script>
子组件:
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
required: true
}
}
}
</script>
(2) 使用$children可以在父组件中访问子组件
- 子组件 -- > 父组件
(1)vue事件方法 :
父组件向子组件传递事件方法,子组件通过$emit触发事件,回调给父组件
父组件:
<template>
<child @msgFunc="func"></child>
</template>
<script>
import child from './child.vue';
export default {
components: {
child
},
methods: {
func (msg) {
console.log(msg);
}
}
}
</script>
子组件:
<template>
<button @click="handleClick">点我</button>
</template>
<script>
export default {
props: {
msg: {
type: String,
required: true
}
},
methods () {
handleClick () {
//........
this.$emit('msgFunc');
}
}
}
</script>
(2) 使用$parent 可以访问父组件的数据。
(3) 通过修改父组件传递的props来修改父组件数据(不推荐)
这种方法只能在父组件传递一个引用变量时可以使用,子面变量不可用
因为引用变量最终无论是父组件中的数据还是子组件得到的props中的数据都是指向同一块内存地址,所以修改了子组件中props的数据即修改了父组件的数据。
但是并不推荐这么做,并不建议直接修改props的值
如果数据是用于显示修改的,在实际开发中可将其放入data中,在需要回传给父组件的时候再用事件回传数据。这样做保持了组件独立以及解耦,不会因为使用同一份数据而导致数据流异常混乱,只通过特定的接口传递数据来达到修改数据的目的,而内部数据状态由专门的data负责管理。
- 非父子组件、兄弟组件之间的数据传递
非父子组件通信,Vue官方推荐使用一个Vue实例作为中央事件总线。
Vue内部有一个事件机制,可以参考源码。
$on方法用来监听一个事件。
$emit用来触发一个事件。
/*新建一个Vue实例作为中央事件总嫌*/
let event = new Vue();
/*监听事件*/
event.$on('eventName', (val) => {
//......do something
});
/*触发事件*/
event.$emit('eventName', 'this is a message.');
-
多层级父子组件通信
-
复杂的单页应用数据管理
vuex
网友评论