vue 数据传递 - provide 与 inject

vue 2.2.0新增了 provide \ inject功能。

官网提示:provide 和 inject主要为高阶插件/组件库提供用例,并不推荐直接用于应用程序代码中。

这对选项需要一起使用,以允许一个祖先向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。这里与react的上下文特性很相似。

注意:这个provide提供的数据正常来说是不会自动更新的,但是如果传递的参数是已监听的对象也是可以做到实时更新的。

//Parent.vue
<template>
    <div class="box">
        <p>发给child的modelMSG: {{modelMSG.msg}}</p>
        <p>
            修改modelMSG:
            <input type="text" v-model="modelMSG.msg" />
        </p>
        <Child :data.sync="modelMSG" />
    </div>
</template>

<script>
import Child from './Child'
export default {
    name: 'Parent',
    components: {
        Child,
    },
    provide() {
        return {
            data: this.modelMSG,
        }
    },
    data() {
        return {
            modelMSG: {
                msg: '发给Child的modelMSG信息',
            },
            name: 'Parent的名字',
        }
    },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
h3 {
    margin: 40px 0 0;
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    display: inline-block;
    margin: 0 10px;
}
.green {
    color: #42b983;
}
.box {
    text-align: left;
    width: 600px;
    margin: 0 auto;
}
input {
    width: 200px;
    height: 35px;
    line-height: 35px;
}
</style>
//Child.vue
<template>
    <div class="hello">
        <p class="red">来自Parent的value: {{data.msg}}</p>
    </div>
</template>

<script>
export default {
    name: 'Child',
    inject: ['data'],
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
    margin: 40px 0 0;
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    display: inline-block;
    margin: 0 10px;
}
.red {
    color: #f00;
}
</style>

猜你喜欢

转载自www.cnblogs.com/hellolol/p/11833361.html