一、概念
二、实践
代码
App
<template><div class="app">我是APP组件<button @click="change">修改数据</button><SonA></SonA><SonB></SonB></div>
</template><script>
import SonA from './components/SonA.vue'
import SonB from './components/SonB.vue'
export default {provide() {return {// 简单类型 是非响应式的color: this.color,// 复杂类型 是响应式的-推荐userInfo: this.userInfo,}},data() {return {color: 'pink',userInfo: {name: '张三',age: 18,},}},methods: {change() {this.color = 'green'// this.userInfo.name = '李四'},},components: {SonA,SonB,},
}
</script><style>
.app {border: 3px solid #000;border-radius: 6px;margin: 10px;
}
</style>
GrandSon
<template><div class="grandSon">我是GrandSon{{ color.color }} - {{ userInfo.name }} - {{ userInfo.age }}</div>
</template><script>
export default {inject: ['color', 'userInfo'],
}
</script><style>
.grandSon {border: 3px solid #000;border-radius: 6px;margin: 10px;height: 100px;
}
</style>
SonA
<template><div class="SonA">我是SonA组件<GrandSon></GrandSon></div>
</template><script>
import GrandSon from '../components/GrandSon.vue'
export default {components:{GrandSon}
}
</script><style>
.SonA {border: 3px solid #000;border-radius: 6px;margin: 10px;height: 200px;
}
</style>
SonB
<template><div class="SonB">我是SonB组件</div>
</template><script>
export default {}
</script><style>
.SonB {border: 3px solid #000;border-radius: 6px;margin: 10px;height: 200px;
}
</style>
展示
非响应式的数据页面展示的数据不改变,data数据改变
-----------------------------------------------------------------------------------------------------------------------------
注:本人是根据黑马程序员的B站教程来学习的,
链接:https://www.bilibili.com/video/BV1HV4y1a7n4/?spm_id_from=333.999.0.0