一、概念解析
成对出现:provide和inject是成对出现的
作用:用于父组件向子孙组件传递数据
使用方法:父组件通过provide提供数据,其他组件可以使用inject注入数据。
二、代码解析
// 父组件
<template>
<div>
<h1>
{{message}}
</h1>
<itemA /> // 使用子组件
</div>
</template>
<script>
import itemA from './item_a.vue' // 引用子组件item_a
export default {
data() {
return {
message: 'provide/inject的学习',
arrs: ['小明', '18', '180'], // 要向子组件传的数组
meg: '传值' // 要向子组件传的值
}
},
methods: {
// 要向子组件传的方法
btn() {
console.log('123456');
}
},
provide() {
return {
arrs: this.arrs, // 传数组
meg: this.meg, // 传值
btn: this.btn // 传方法
}
},
components: { itemA }, // 注册子组件item_a
}
</script>
<style>
</style>
// 子组件item_a
<template>
<div>
<h2>{{message}}</h2>
<button @click="btnT">按钮</button>
<itemB /> // 使用子组件
</div>
</template>
<script>
import itemB from './item_b.vue' // 引用子组件item_b
export default {
data() {
return {
message: 'item_a:' + this.meg
}
},
methods: {
btnT() {
this.btn()
}
},
inject: ['meg', 'btn'], // 注入(接收)父组件传来的数据
components: { itemB }, // 注册子组件item_b
}
</script>
<style>
</style>
// 子组件item_b
<template>
<div>
<h3>item_b:</h3>
<h3 v-for="n in arrs">{{n}}</h3> // 遍历数组
</div>
</template>
<script>
export default {
data() {
return {
message: this.arrs // 直接使用,记得加this
}
},
inject: ['arrs'] // 接收父组件传来的数组数据
}
</script>
<style>
</style>
运行结果: