简体   繁体   中英

How can I use component specific attributes on dynamic components in Vue.js?

I have two dynamic components which I'm showing using the component element.

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

One of the components needs the prop resources whereas the other emits the custom event resourceAdded . Everything works fine except I get the error message 'Extraneous non-emits event...' and 'Extraneous non-emits props...' which I understand because it is also trying to pass the props and emit the custom event from the component that doesn't have props or emit specified. How can I work around this without having to specifiy the emit and props in both components? Or is that just the way to do it?

FIRST COMPONENT - only emits

<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>

SECOND COMPONENT - needs only props

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

There is a provide / inject feature in Vue.js which allows for specific data and functions communication between parents and children in Vue.js. I found it to work nice for me here, and it is also good for passing some data/functions to or from a deeply nested child, so you don't have to pass it through all of its ancestors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM