vue—依赖注入

使用场景:当组件层级较深,然后需要使用到根组件中的某些值,就需要使用到依赖注入

依赖注入的基本内容就是关于 provide  和  inject

根组件中使用provide

export default {
        name: 'app',
        data(){
            return {
                msg:'Welcome to Your Vue.js App'
            }
        },
        provide(){
            return {
                msg:this.msg
            }
        },
}

子代组件中使用  inject 接收参数

export default{
        data(){
            return {
                children:'this is children component.'
            }
        }
        inject:['msg'],
}
//使用方式
<span>{{msg}}</span> // this.msg

注意事项:

1.依赖注入是非响应的,需要去通过其他的手段去监听

2.开发中建议使用Vuex

原文地址:https://www.cnblogs.com/peilin-liang/p/12010230.html