美文网首页
Vue prop 传值和 provide→inject传值的区别

Vue prop 传值和 provide→inject传值的区别

作者: 李牧敲代码 | 来源:发表于2019-03-08 10:21 被阅读0次

应用场景

prop传值是平常Vue父子组件之间主要传值的方式,并且这是响应式的。但是,如果你有个应用嵌套了多层组件,然后多个子组件需要用到父组件的某个值,这个时候通过provide→inject的方式是比较方便的。

//父组件
<template>
    <div>
        <componentA></componentA>
    </div>
</template>

<script>
    // @ is an alias to /src
    import componentA from '../components/componentA'
    export default {
        name: 'home',
        data() {
            return {
                name: 'wcx'
            }
        },
        provide() {
            return {
                name: name
            }
        },
        components: {
            componentA,
        }
    }
</script>
//子组件
<template>
    <div>
        componentA<input type="text" value="name">
        <componentB></componentB>
    </div>
</template>
<script>
    import componentB from './componentB';
export default {
    name: 'componentA',
    inject: ['name'],
    components: {
        componentB
    }
}
</script>
<style lang="">
    
</style>
// 孙子组件
<template>
    <div>
        componentB{{name}}
        <input type="text" value="name">
    </div>
</template>
<script>
export default {
    name: 'componentB',
    inject: ['name']
}
</script>
<style lang="">
    
</style>

结果图:

image

总结

prop:

优点: 响应式
缺点: 递归传值比较麻烦

provide→inject:

优点: 递归传值比较容易
缺点: 非响应式

【完】

相关文章

  • Vue prop 传值和 provide→inject传值的区别

    应用场景 prop传值是平常Vue父子组件之间主要传值的方式,并且这是响应式的。但是,如果你有个应用嵌套了多层组件...

  • Vue 3.0 Provide和Inject实现共享数据

    Provide和Inject可以在祖(父)组件和子(孙)组件间实现传值。相比prop只能父子之间传值而言,Prov...

  • vue组件传值和函数调用

    1,父组件传值给子组件 vue2.0 vue3.0(provide(提供)/inject(注入)用法) 2,父组件...

  • vue组件的8中传值方式

    今天我介绍一下vue的8种传值方式: 这里我们只介绍: parent provide/inject EventBu...

  • Vue - 传值

    Vue 传值有两种:1)父组件向子组件传值(属性传值,Prop传值)2)子组件向父组件传值 一、父组件向子组件传值...

  • provide/inject

    provide/inject能够用于实现祖先和后代之间的传值parent 父组件 child 组件 grand 孙...

  • vue3的父子组件传值

    在vue3的父子组件传值中提供了一种新的方式:provide/inject官网地址:https://www.jav...

  • vue组件隔代传值 provide / inject

    一般在层级不多的组件中,我们都是用props去和子组件通信,但是如果层级比较多了,props用起来就显得不是那么灵...

  • vue provide 和 react provider

    vue provide/inject 作用:祖先组件向其所有子孙后代传值 这对选项需要一起使用,以允许一个祖先组件...

  • 2019-03-13

    vue父子组件传值,(父组件向子组件传值用prop ,子组件向父组件传值:子组件调用父组件方法值以参数的方式传递)...

网友评论

      本文标题:Vue prop 传值和 provide→inject传值的区别

      本文链接:https://www.haomeiwen.com/subject/kyplpqtx.html