将父组件的属性传递给 Vue 中所有被嵌入的子组件 [英] Pass properties from parent component to all transcluded children component in Vue

查看:40
本文介绍了将父组件的属性传递给 Vue 中所有被嵌入的子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当这些属性被嵌入时(内容分发语法),我想将一些属性从父级传递给他的所有子级.在这种情况下,父母不知道(据我所知)他的孩子,所以我不知道如何进行.

I would like to pass some properties from a parent to all of his children when those are transcluded (content distribution syntax). In this case, the parent doesen't know (as far as I know) his children, so I don't know how to proceed.

更具体地说,我想要一种写法:

More specificly, I want a way to write this :

<my-parent prop1="foo" prop2="bar">
    <my-children></my-children> <!-- Must know content of prop1 and prop2 -->
    <my-children></my-children> <!-- Must know content of prop1 and prop2 -->
</my-parent>

而不必写这个:

<my-parent prop1="foo" prop2="bar">
    <my-children prop1="foo" prop2="bar"></my-children>
    <my-children prop1="foo" prop2="bar"></my-children>
</my-parent>

有可能吗?谢谢.

推荐答案

这是我的解决方案,这可能不是什么大问题,但对于我现在想做的事情来说,这是最干净的解决方案.原则是创建计算属性,如果它们存在,将使用自己的组件 prop,否则获取 $parent 值.然后就可以在 this._prop 中访问真正的 prop.

Here is my solution, that's probably not a great deal, but that's the cleanest solution for what I want to do right now. The principle is to create computed properties that will use own component prop if they exist, or get $parent values otherwise. The real prop would then be accessible in this._prop.

Vue.component('my-children', {
    props: ["prop1", "prop2"],
    template: "<div>{{_prop1}} - {{_prop2}}</div>",
    computed: {
        _prop1: function() {
            return this.prop1 || this.$parent.prop1;
        },
        _prop2: function() {
            return this.prop2 || this.$parent.prop2;
        }
    }
});

这是一个混合生成器,它以更优雅的方式完成此操作,并且可能具有多个级别:

Here is a mixin generator that does that in a more elegant way, and with, possibly, multiple levels :

function passDown(...passDownProperties) {
    const computed = {};
    passDownProperties.forEach((prop) => {
        computed["_" + prop] = function() {
            return this[prop] || this.$parent[prop] || this.$parent["_" + prop];
        };
    });
    return { computed };
}

Vue.component('my-children', {
    props: ["prop1", "prop2"],
    template: "<div>{{_prop1}} - {{_prop2}}</div>",
    mixins: [passDown("prop1", "prop2")]
});

这篇关于将父组件的属性传递给 Vue 中所有被嵌入的子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆