一:
父组件向子组件传值:
father:
<template>
<father>
<son :message="msg"></son> (message动态绑定msg数据,必须v-bind:动态绑定)
</father>
</template>
<script>
export default {
data(){
return {
msg: "父亲"
}
}
}
</script>
son:
<template>
<div>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
props:["message"]
data(){
return {}
}
</script>
}
或者
props: {
message: {
type: String, //类型为字符串
default:"默认值" //可设置默认值
}
}
props: {
message: {
type: Array, //类型为数组
default: [‘f’,‘a’,‘z’] //默认值
}
}
二:
子组件向父组件传值
因为vue中子组件不能更改父组件中的内容,因此通过子组件触发一些事件来传值给父组件。
son:
<template>
<button @click ='setValue'>点击</button>
</template>
<script>
export default {
data(){
return {
value: "儿子"
}
},
methods:{
setValue:function(){
this.$emit('sendValue',this.value); //this.value为向父组件传递的数据
}
}
}
</script>
parent:
<template>
<div id="app">
<son @sendValue="receive"></son> //监听由子组件触发的 'sendValue'事件,然后调用receive方法来更改数据
<p>{{value}}</p>
</div>
</template>
<script>
export default {
data(){
return{
value:"father"
}
},
methods: {
receive:function(val) {
this.value = val;
}
}
}
</script>
三:
非父子组件之间的通讯
有时候两个非父子关系组件也需要通信 。通常,使用一个空的 Vue 实例作为中央事件总线,类似于一个“中转站”,进行发送和接收数据。
commonEvent.js
import Vue from ‘vue’
var station = new Vue() //创建事件"中转站"
export default station
或者
import Vue from ‘vue’
export default new Vue
X.vue
<template>
<button @click="bClick">content</button >
</template>
// 触发组件X中的事件
<script>
import eventdata from './commonEvent.js' (这个路径看你的commonEvent.js文件放哪里)
export default {
methods: {
bClick(){
eventdata .$emit('send',this.message);
}
}
}
</script>
Y.vue
// 在组件Y监听事件
<template>
< div>{{message}}< /div>
</template>
<script>
import eventdata from './commonEvent.js'
export default {
data(){
return{
message:"默认值"
}
}
}
</script>
(调用created钩子函数进行监听事件的初始化)
created() {
eventdata .$on(‘send’, function(val){ //接收事件
this.message = val
})
}