vue 组件传值的方法有很多,但是项目中有些时候需要隔代传值,例如从曾祖父代网曾孙子代传值,普通的父子传值就比较麻烦,而使用vuex又不太划算,那么这个时候可以使用provide/inject方法;可以隔很多代往下传,但是必须是从上往下传
代码如下所示:
爷爷组件代码如下:
<template>
<div class="home">
<button @click="tap">爷爷组件传值</button>
<child1></child1>
</div>
</template>
<script>
import child1 from "./child1.vue";
export default {
name: "Home",
data() {
return {
msg: {
aaa: "33",
},
};
},
provide() {
return {
//返回函数形式是为了响应式
grandpaValue: () => this.msg,
};
},
components: {
child1,
},
methods: {
tap() {
this.msg = [1, 2, 3];
},
},
};
</script>
<style scoped>
.home {
width: 800px;
height: 800px;
border: 1px solid blue;
}
</style>
父亲组件代码如下:
<template>
<div class="box-wrap">
<child11></child11>
<child22></child22>
</div>
</template>
<script>
import child11 from "./child1-1.vue";
import child22 from "./child1-2.vue";
export default {
name: "",
components: {
child11,
child22,
},
data() {
return {};
},
};
</script>
<style scoped>
.box-wrap {
width: 600px;
height: 600px;
border: 1px solid red;
}
</style>
孙子代码如下:
<template>
<div class="box">
{{val}}
</div>
</template>
<script>
export default {
inject: {
grandpaValue: {
// 键名
from: "grandpaValue", // 来源
default: "默认值", // 爷爷组件未传值,grandpaValue的默认值,爷爷传值的话grandpaValue是一个函数
},
},
computed: {
val() {
//如果为函数,说明有值,就调用this.grandpaValue()取值,
// 如果没有就直接返回this.grandpaValue默认值
if (typeof this.grandpaValue === "function") {
return this.grandpaValue();
} else {
return this.grandpaValue;
}
},
},
watch: {
val() {
console.log("数据改变时,孙子组件做的操作");
},
},
data() {
return {};
},
};
</script>
<style scoped>
.box {
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>