2

Trying to get an option to be selected by default if selected is present on the option object

This is what i have:

<template>
    <select v-model="model" :placeholder="placeholder">
        <option v-for="option in options" :value="option.value" :selected="option.selected">{{option.label}}</option>
    </select>
</template>

<script>
export default {
    props: {
        model: {
            default: null
        },
        placeholder: {
            default: null
        },
        options: {
            default: null
        }
    }
};
</script>

This sets selected attribute correctly, i can see it in element explorer This doesnt seem to work, since its only an attribute, if i check the element, the "selected" property on it is false! How do i set selected property of the option element?

1
  • I think that you need to remove the :selected="option.selected" as it is supposed to be set by the v-model attribute Commented Dec 2, 2016 at 14:28

2 Answers 2

1

You just need to set the originally selected value to the value of the v-model, i.e.

new Vue({
    el: '#app',
    data: {
        options: [
        	{
            	value: 'foo',
                label: 'foo label',
            },
        	{
            	value: 'bar',
                label: 'bar label',
            },
        	{
            	value: 'baz',
                label: 'baz label',
            },        
        ],
        selected: 'bar',
    }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">

    <select v-model="selected">
        <option v-for="option in options" :value="option.value">{{option.label}}</option>
    </select>

</div>

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

Comments

0

Found the issue, the "data" property for my component was coming from somewhere else. So i needed to find where it was coming from.

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.