https://cn.vuejs.org/v2/api/#provide-inject
https://blog.csdn.net/Min_Fox/article/details/123428325
- 父级页面(src/views/user/member/index.vue)
<template>
<div class="user">
<div class="">
<div>会员用户</div>
</div>
<child></child>
</div>
</template>
<script>
import child from "@/components/child";
export default {
components: {
child,
},
name: 'Member',
data() {
return {
name: 'hszz',
obj: {
name: 'hszz'
},
}
},
provide() {
return {
name: this.name, // 父级传递的非响应式数据
xxName: () => this.name, // 父级传递的响应式数据方法1-通过工厂函数
obj: this.obj, // 父级传递的响应式数据方法2-传递对象
changeData: this.changeData, // 暴露给子组件的方法,子组件可通过此方法传值给父级
}
},
methods: {
changeData(value) {
this.name = value
this.obj.name = value
}
},
}
</script>
- 子组件(src/components/child/index.vue)
<template>
<div>
<div>子组件</div>
<div>父级的非响应数据:{{ name }}</div>
<div>父级的响应数据1.1:{{ cName }}</div>
<div>父级的响应数据1.2:{{ xxName() }}</div>
<div>父级的响应数据2.1:{{ obj.name }}</div>
<el-input v-model="childData"></el-input>
<el-button type="primary" @click="childChangeData">
点击把输入框数据传递给父级,修改父级数据
</el-button>
</div>
</template>
<script>
export default {
name: "child",
data() {
return {
childData: "",
};
},
inject: ['name', 'changeData', 'obj', 'xxName'],
methods: {
childChangeData() {
this.changeData(this.childData)
}
},
computed: {
cName() {
return this.xxName()
}
},
};
</script>
image.png
image.png
网友评论