简体   繁体   English

Vue.js:设置 html<option>通过“selected”标记为默认值不起作用

[英]Vue.js: setting html <option> tag to default via "selected" doesn't work

I want to set one of the available <option> tags to default.我想将可用的<option>标签之一设置为默认值。 On the <select> tag I am using v-model and I know that the vue.js documentation states the following in regard to this:<select>标签上,我使用的是v-model并且我知道vue.js文档对此有以下说明:

v-model will ignore the ... selected attributes found on any form elements. v-model将忽略在任何表单元素上找到的 ... selected属性。 It will always treat the Vue instance data as the source of truth.它将始终将 Vue 实例数据视为真实来源。 You should declare the initial value on the JavaScript side, inside the data option of your component.您应该在 JavaScript 端,在组件的 data 选项内声明初始值。

So I am using the selected attribute with v-bind and passing either directly true to it or through a variable in the data option.所以我将selected属性与 v-bind 一起使用,并直接将true传递给它或通过 data 选项中的变量传递。 Unfortunately it doesn't work.不幸的是它不起作用。 Here is an jsfiddle .这是一个jsfiddle

And here is the example code:这是示例代码:

HTML HTML

<div id="app">
  <select v-model="selectedData" @change="doSomething">
    <option :selected="true" value="">
      Please select account
    </option>
    <option 
      v-for="data in myData"
      :key="data.id"
      :value="data.val"
    >
      {{ data.val }} 
    </option>
  </select>
{{ selectedData }}
</div>

JavaScript JavaScript

new Vue({
  el: "#app",
  data: {
    selected: true,
    selectedData: null,
    myData: [
      { id: 1, val: "abc" },
      { id: 2, val: "def" },
      { id: 3, val: "ghi" },
      { id: 4, val: "jkl" },
    ]
  },
  methods: {
    doSomething: function(){
        console.log('hello')
    }
  }
})

The <select> tag's model is what is actually driving the chosen item in the drop down. <select>标签的模型是实际驱动下拉列表中所选项目的原因。

<select v-model="selectedData" @change="doSomething">

Change your "default" option to the following将您的“默认”选项更改为以下内容

    <option value="-1">
      Please select account
    </option>

and in your data object, instead of having null assigned to your selected value on initialization, set it to -1并且在您的数据对象中,不要在初始化时将null分配给您选择的值,而是将其设置为 -1

data: {
    selectedData: -1,
    myData: [
      { id: 1, val: "abc" },
      { id: 2, val: "def" },
      { id: 3, val: "ghi" },
      { id: 4, val: "jkl" },
    ]
  },

You'll want to set the initial value of the property bound with v-model , so selectedData: '' (instead of null ).您需要设置与v-model绑定的属性的初始值,因此selectedData: '' (而不是null )。 I'm not sure if I'm missing something else, but this is how I always do it.我不确定我是否遗漏了其他东西,但我总是这样做。

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

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