vue中v-if出现的问题

<div v-if="loginType ==='username'">
    <label >username</label>
    <input placeholder="enter your username" key="username-input">
  </div>
  <div v-else>
    <label>email</label>
    <input placeholder="enter your email" key="email-input">
  </div>

我写完上面的代码后,vue-cli马上出现下面的错误


./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-f68cdee0","hasScoped":true,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/DemoIf.vue
(Emitted value instead of an instance of Error) 
  Error compiling template:
  
  <div>
  <div v-if="loginType ==='username'">
    <label >username</label>
    <input placeholder="enter your username" key="username-input">
  </div>
  <div v-else-if="loginType ==='email'">
    <label>email</label>
    <input placeholder="enter your email" key="email-input">
  </div>
  </div>
  <buttob @click="changed"></buttob>
  
  - 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.

 @ ./src/components/DemoIf.vue 11:0-362
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js
阅读 4.6k
4 个回答

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. 组件模板应该只包含一个根元素

<template> 
 <div>
    组件内容
 </div>
</template> 

楼上说了,template里面只能有一个根元素

<template> 
 <div v-if="loginType ==='username'">
    ....
 </div>
 <div v-else>
    ....
 </div>
</template> 

改成

<template> 
   <div>
     <div v-if="loginType ==='username'">
        ....
     </div>
     <div v-else>
        ....
     </div>
   </div>
</template> 

在vuejs中,特别是vue2.0以后,一个组件的最外层是需要一层"根元素"进行包裹,否则会出错,在这vue1.0中是没有的。那么对于vueJs中的v-if的用法,如果你是直接作用在一个组件的"根元素"上面,就会报错。应该这样改:

<template> 
 <div v-if="loginType ==='username'">
    ....
 </div>
 <div v-else>
    ....
 </div>
</template> 

或者
<template> 
  <div>
     <div v-if="loginType ==='username'">
    ....
     </div>
  </div>

</template>

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.

这个报错信息已经说了,template里面只能有一个根元素

看你的报错信息,感觉不是v-if,v-else的问题,
是 <buttob @click="changed"></buttob> 没有写在上面的div里面,导致页面有两个根元素了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题