Vue js error: Component template should contain exactly one root element

后端 未结 8 2145
予麋鹿
予麋鹿 2020-11-29 04:37

I don\'t know what the error is, so far I am testing through console log to check for changes after selecting a file (for uploading).

When I run $ npm run watc

8条回答
  •  余生分开走
    2020-11-29 04:54

    Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

    The right approach is

    
    

    The wrong approach

    
    

    Multi Root Components

    The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

    As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

    Here is how you can create a simple functional component.

    Vue.component('my-component', {
        // you must set functional as true
      functional: true,
      // Props are optional
      props: {
        // ...
      },
      // To compensate for the lack of an instance,
      // we are now provided a 2nd context argument.
      render: function (createElement, context) {
        // ...
      }
    })
    

    Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

    
    

    Now if we take a look at NavBarRoutes template

    
    

    We cant do some thing like this we will be violating single root component restriction

    Solution Make this component functional and use render

    {
    functional: true,
    render(h, { props }) {
     return props.routes.map(route =>
      
  • {route.title}
  • ) }

    Here you have it you have created a multi root component, Happy coding

    Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

提交回复
热议问题