如何在 select 中添加条件? (Vue.JS 2)

How can I add condition in select ? (Vue.JS 2)

我有这样的 vue 组件:

<script>
    export default{
        template: '\
            <select class="form-control" v-on:change="search">\
                <option v-for="option in options" v-bind:value="option.id ? option.id+\'|\'+option.name : \'\'">{{ option.name }}</option>\
            </select>',
        mounted() {
            this.fetchList();
        },
        ...
    };
</script>

有效。没有错误

但是,我想在 select

中再次添加条件

满足条件则selected

我这样添加条件:

template: '\
            <select class="form-control" v-on:change="search">\
                <option v-for="option in options" v-bind:value="option.id ? option.id+\'|\'+option.name : \'\'" option.id == 1 ? \'selected\' : \'\'>{{ option.name }}</option>\
            </select>',

存在这样的错误:

[Vue warn]: Property or method "option" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

我该如何解决?

这应该有效。像这样更改您的代码。

<option v-for="option in options" v-bind:value="option.id ? option.id+\'|\'+option.name : \'\'" v-bind:selected="option.id == 1">{{ option.name }}</option>\

由于 selected 是布尔属性,您必须使用 v-bind:selected="<condition>"。这将根据条件的结果插入属性。

我会改成 v-model 基于:

<select @change="search" v-model="select">
  <option v-for="option in options" :value="option.id">
    {{ option.name }}
  </option>
</select>

<script>
export default {
  props: {
    value: [Number, String]
  },
  data() {
    return { select: this.value };
  },
  watch: {
    value: function (val) {
      this.select = val;
    }
  },
  methods: {
    // ...
  }
};
</script>