inheritAttrs 和 attrs
/*
* 目錄結構:
* child.vue(子組件)
* components--> Child-->
* child2.vue(子子組件)
*
* pages-->parent.vue(父組件)
*/
// 父組件
<template>
<div v-color>
<child :value="text" :count="count"></child>
</div>
</template>
<script>
import child from "../components/Child/child";
export default {
data() {
return {
text: "父組建值",
count: 66666
};
},
provide() {
return {
parent: this
};
},
components: {
child
}
};
</script>
// 子組件 child.vue
<template>
<div>
<my-child v-bind="$attrs"></my-child>
</div>
</template>
<script>
import myChild from "./child2";
export default {
props: {
value: {
type: String,
default: ""
}
},
inheritAttrs: false, // 讓傳遞給子組建的值隱藏,F12查看原本在dom上存在count="66666"標示,加上后可以在dom上不顯示
components: {
myChild
},
mounted() {
console.log(this.$attrs);
}
};
</script>
// 子子組件 child2.vue
<template>
<div>我是最子子組建:{{$attrs.count}}</div>
</template>
<script>
export default {
mounted() {
console.log("22222:", this.$attrs) // 可以跨組件獲取祖先級傳入的值
}
};
</script>
provide 和 inject
// 父組件 parent.vue 非響應寫法
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from "../components/Child/child";
export default {
data() {
return {
};
},
provide: {
parent: '父組建值'
},
components: {
child
}
};
</script>
// 組件child.vue 引用 child2.vue(省略)
// 子子組件child2.vue
<template>
<div>我是子子組建:{{this.parent}}</div>
</template>
<script>
export default {
mounted() {
console.log("另外一種傳值方式:", this.parent);
},
inject: ["parent"]
};
</script>
// 父組件 parent.vue 響應寫法
<template>
<div v-color>
<child :value="test" :count="count"></child>
</div>
</template>
<script>
import child from "../components/Child/child";
export default {
data() {
return {
text: ''
};
},
provide() {
return {
parent: this
};
},
components: {
child
}
};
</script>
// 組件child.vue 引用 child2.vue(省略)
// 子子組件child2.vue
<template>
<div>我是子子組建:{{this.parent.text}}</div>
</template>
<script>
export default {
mounted() {
console.log("另外一種傳值方式:", this.parent);
this.parent.text = "卧槽,無情"; // 可以改變父級狀態值並更新頁面
},
inject: ["parent"]
};
</script>