【问题标题】:How can I use component specific attributes on dynamic components in Vue.js?如何在 Vue.js 中的动态组件上使用组件特定属性?
【发布时间】:2021-05-21 11:52:21
【问题描述】:

我有两个使用组件元素展示的动态组件。

  <keep-alive>
    <component :is="activeOption" :resources="resources" @resourceAdded="addToList"></component>
  </keep-alive>

其中一个组件需要 resources 属性,而另一个发出自定义事件 resourceAdded。一切正常,除了我收到错误消息“Extraneous non-emits event...”和“Extraneous non-emits props...”,我理解这是因为它也在尝试传递道具并从组件发出自定义事件没有指定道具或发射。我怎样才能解决这个问题而不必在两个组件中指定发射和道具?或者这就是这样做的方式?

第一个组件 - 只发射

<script>
    export default {
        emits: ['resourceAdded'],
        // props: {
        //     resources: {
        //         type: Array,
        //         required: true
        //     }
        // }, NO  PROPS ERROR IF THIS IS SPECIFIED
        data() {
            return {
                errorMsg: false
            }
        },
        methods: {
            addNewResource() {
                const name = this.$refs.name.value
                const description = this.$refs.description.value
                const link = this.$refs.link.value
    
                if(name === '' || description === '' || link === ''){
                    this.errorMsg = true
                }else{
                    this.$emit("resourceAdded", name, description, link)
                }
            }
        }
    }
    </script>

第二个组件 - 只需要道具

<script>
export default {
    props: {
        resources: {
            type: Array,
            required: true
        }
    },
    // emits: ['resourceAdded'] NO EMITS ERROR IF THIS IS SPECIFIED
}
</script>

【问题讨论】:

  • 在渲染动态组件时可能最好使用v-bindv-on&lt;component v-bind="some_attributes_object" v-on="some_listeners_object" /&gt;

标签: vue.js vue-component vue-dynamic-components


【解决方案1】:

Vue.js 中有一个提供/注入功能,它允许在 Vue.js 中的父子之间进行特定的数据和函数通信。我发现它在这里很适合我,而且它也适合将一些数据/函数传入或传出一个深度嵌套的子元素,因此您不必将它传递给它的所有祖先。

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2017-04-30
    • 2021-06-27
    • 2017-08-17
    • 2021-12-28
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2020-04-03
    相关资源
    最近更新 更多