1

I have vue component like this :

<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>

It works. No error

But, I want to add condition again in select

If it meets the conditions then selected

I add condition like this :

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>',

There exist error like this :

[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.

How can I solve it?

2 Answers 2

4

This should work. Change your code like this.

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

Since selected is boolean attribute you'll have to use v-bind:selected="<condition>". This will insert the attribute based on the conditional's result.

Sign up to request clarification or add additional context in comments.

Comments

4

I would change to a v-model based:

<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.