簡體   English   中英

選擇選項不起作用Vue js

[英]Select Options are not working Vue js

在使用Vue練習不同的元素時,我被困在這一點上。 當我嘗試制作option template組件並嘗試在select使用它時,它不起作用。

 Vue.component('todo-item', { props: ['todo'], template: '<option v-bind:value="todo.id">{{todo.text}}</option>' }) var app = new Vue({ el: '#app', todo : [], data: { message: 'Hello Vue!123', buttonText: 'Click Me', seen:true, groceryList: [ { id: 0, text: 'Vegetables' }, { id: 1, text: 'Cheese' }, { id: 2, text: 'Whatever else humans are supposed to eat' } ] }, methods:{ buttonClick:() => { app.message="Button Clicked"; app.seen=true; } } }) 
 table{ width:50%; border: solid 2px; } td{ border: solid 1px; text-align:center } ol{ list-style-type : none; } select{ width:30% } 
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id ="app"> <p v-if="seen">{{message}}</p> <button v-on:click="buttonClick"> {{buttonText}} </button> <br><br> <input v-model="message"></input> <br> <br> <select> <todo-item v-for="grocery in groceryList" :todo="grocery"> </select> <todo-item v-for="grocery in groceryList" :todo="grocery"> </todo-item> <ul v-for="grocery in groceryList"> <li> {{ grocery.text }} </li> </ul> </div> 

我嘗試在select標記之外進行嘗試,其他任何html也可以正常工作,例如input

Codepen鏈接

如果您要我做任何事情來解釋我的問題,請在評論部分告訴我。 謝謝

我認為這里出問題的不是Vue或Javascript。 這是瀏覽器處理無效HTML的方式。

select應該只包含option

如果您使用HTML進行此操作(假設根本不使用Javascript),

<select>
   <todo-item></todo-item>
   <todo-item></todo-item>
   <todo-item></todo-item>
</select>

瀏覽器會刪除todo-item因為它是無效的。 https://codepen.io/jacobgoh101/pen/pZZQRz

在您的情況下,到Vue初始化時,瀏覽器已經刪除了無效的HTML,即todo-item

您也可以通過將select放入組件中來避免這種情況。 演示: https : //codepen.io/jacobgoh101/pen/WKKYGm

Vue.component('basic-select', {
  template:`
<select>
  <slot></slot>
</select>
`
});

並像這樣使用

<basic-select>
   <todo-item v-for="(grocery,i) in groceryList" :key="i" :todo="grocery">
</basic-select>

這樣,Vue功能將被應用,而不會被瀏覽器弄亂。

僅當您直接在瀏覽器中使用Vue而不使用構建工具和vue-loader時,才會發生此類問題。 在典型的vue-cli生成的項目中,所有html模板都在Vue單個文件組件中處理,並且所有html都將由Vue編譯,然后瀏覽器使用

如果要使用select標簽,則需要在其中使用option標簽。

在vue文檔中:

<select v-model="selected">
  <!-- inline object literal -->
  <option v-bind:value="{ number: 123 }">123</option>
</select>

在您的示例中,您可以像這樣使用它:

<select v-model="selectedGrocery">
  <option v-bind:value="grocery.id" v-for="grocery in groceryList">
      {{grocery.text}}
  </option>
</select>

在選擇標簽中,在v-for之前進行v-bind。 所以這樣做:

<select v-model="selectedGrocery">
  <option v-bind:value="grocery.id" v-for="grocery in groceryList">
      {{grocery.text}}
  </option>

不是這個:

<select v-model="selectedGrocery">
  <option  v-for="grocery in groceryList" v-bind:value="grocery.id">
      {{grocery.text}}
  </option>
</select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM