close

How can I set selected option selected in vue.js 2?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I set selected option selected in vue.js 2? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I set selected option selected in vue.js 2?

  1. How can I set selected option selected in vue.js 2?

    can I set selected option selected in vue.js 2
    Vue.directive('attr', (el, binding) => { if (binding.value === true) binding.value = '' if (binding.value === '' || binding.value) { el.setAttribute(binding.arg, binding.value) } })
    You can then utilise v-attr to set an attribute, eg:
    <option value="Western Australia" v-attr:selected="form.state == 'Western Australia'">Western Australia</option>

  2. How can I set selected option selected in vue.js 2?

    can I set selected option selected in vue.js 2
    Vue.directive('attr', (el, binding) => { if (binding.value === true) binding.value = '' if (binding.value === '' || binding.value) { el.setAttribute(binding.arg, binding.value) } })
    You can then utilise v-attr to set an attribute, eg:
    <option value="Western Australia" v-attr:selected="form.state == 'Western Australia'">Western Australia</option>

Method 1

The simplest answer is to set the selected option to true or false.

<option :selected="selectedDay === 1" value="1">1</option>

Where the data object is:

data() {
    return {
        selectedDay: '1',
        // [1, 2, 3, ..., 31]
        days: Array.from({ length: 31 }, (v, i) => i).slice(1)
    }
}

This is an example to set the selected month day:

<select v-model="selectedDay" style="width:10%;">
    <option v-for="day in days" :selected="selectedDay === day">{{ day }}</option>
</select>

On your data set:

{
    data() {
        selectedDay: 1,
        // [1, 2, 3, ..., 31]
        days: Array.from({ length: 31 }, (v, i) => i).slice(1)
    },
    mounted () {
        let selectedDay = new Date();
        this.selectedDay = selectedDay.getDate(); // Sets selectedDay to the today's number of the month
    }
}

Method 2

Another way, which I often find more reliable, is you could add a directive to your app.js or wherever you are initiating your VueJS, eg:

Vue.directive('attr', (el, binding) => {
  if (binding.value === true) binding.value = ''
  if (binding.value === '' || binding.value) {
    el.setAttribute(binding.arg, binding.value)
  }
})

You can then utilise v-attr to set an attribute, eg:

<option value="Western Australia" v-attr:selected="form.state == 'Western Australia'">Western Australia</option>

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment