简体   繁体   English

默认选择的值在 Vue.js 中不起作用

[英]Default selected value not working in Vue.js

I'm trying to set default selected value for my dropdown list.我正在尝试为我的下拉列表设置默认选择值。 My code looks like this:我的代码如下所示:

        <select v-model="newSelectedUnit" @change="selectUnit(newSelectedUnit)" class="custom-select">
          <option v-for="unit in units" :key="unit.id" :value="unit.id" :selected="unit.id == Selectedunit.id">{{ unit.name }}</option>
        </select>

but there's no default selected value.但没有默认选择值。 I already tried to hardcoded Selectedunit.id to 32712 (which is one of the unit's IDs):我已经尝试将Selectedunit.id硬编码为32712 (这是单元的 ID 之一):

            <select v-model="newSelectedUnit" @change="selectUnit(newSelectedUnit)" class="custom-select">
              <option  v-for="unit in units" :key="unit.id" :value="unit.id" :selected="unit.id == 32712">{{ unit.name }}</option>
            </select>

In Chrome inspector there's an <option> tag with value of 32712 :在 Chrome 检查器中有一个<option>标记,其值为32712

<option value="32712">CYLINDER</option>

but it's not selected by default.但默认情况下未选中。

EDIT: I noticed that there's a problem with selected atribute.编辑:我注意到selected属性存在问题。 In above example, if i set another attribute: :selectedXXX="unit.id == 32712" i've got expected attribute in Chrome dev tools:在上面的示例中,如果我设置另一个属性: :selectedXXX="unit.id == 32712" 我在 Chrome 开发工具中获得了预期的属性:

<option selectedXXX="true" value="32712">CYLINDER</option>

EDIT2: If I remove v-model="newSelectedUnit" I've got selected value set correctly! EDIT2:如果我删除v-model="newSelectedUnit"我选择的值设置正确! But why?但为什么?

Use either " @change and :selected " or " v-model ", but not both.使用“ @change ”和“ :selected ”或“ v-model ”,但不能同时使用。

Now the v-model on <select> will try to select the unit based on the value in newSelectedUnit现在<select>上的v-model将尝试根据newSelectedUnit中的值选择单位

If the initial value of your v-model expression does not match any of the options, the element will render in an “unselected” state.如果您的 v-model 表达式的初始值与任何选项都不匹配,则该元素将呈现为“未选择”状态。

https://v2.vuejs.org/v2/guide/forms.html#Select https://v2.vuejs.org/v2/guide/forms.html#Select

If you are using materialize css template, it's with a如果您使用物化 css 模板,它带有

select { display:none }

add in your default app css添加您的默认应用程序 css

select: { display: block }

it'll appear again!它会再次出现!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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