父到子:
father.vue中:
<router-view :data="d"></router-view>
data() {
return {
d: "发送给兄弟的数据"
};
},
son.vue中:(在export defaullt内部添加属性props)
props: ["data"]
然后就可以在子组件中直接使用{{data}}
<h1>{{ data }}</h1>
子到父:
son.vue中:
data() {
return {
msg: "传给父组件"
};
},
mounted() {
this.$emit("toparent", this.msg); //传递数据给父组件
}
father.vue中:
<router-view @toparent="get"/>
data() {
return {
msg: "原来的数据"
};
},
methods: {
get(a) {
this.msg = a;
}
},
兄弟组件传值:
可以在src文件夹下新建一个kong.js,内容为:
//创建空对象用于兄弟组件之间的传值
import Vue from "vue";
var kong = new Vue({});
export { kong };
brother1.vue中:(发送)
<button @click="fn">兄弟传值</button>
import { kong } from "../kong.js";
data() {
return {
d: "发送给兄弟的数据"
};
},
methods: {
fn() {
kong.$emit("tobrother", this.d); //传递数据给兄弟组件
}
},
brother2.vue中:(接收)
import { kong } from "../kong.js";
mounted() {
kong.$on("tobrother", function(d) {
console.log(d);
});
}
其他传值方式:
1.子获取父的值:直接在子组件中this.$parent.msg即可获取到父组件的值。
2.父获取子的值:在father.vue中
<router-view ref="child"/>
mounted() {
console.log(this.$refs.child.msg); //主动获取子组件的数据
}