2

I am a freshy with vue.js and trying to create a component for my select boxes. I am having difficulty with wanting to pass a default value to the select through a parent component.

right now i have this in the parent component

<div class="row">
  <div class="col-md-4">
    <active-dropdown :selected='selected', :options = 'active_options', @update = 'update_selected'></active>
  </div>
</div>

here is the component for dropdown

Vue.component 'active-dropdown',
  template: '#active-dropdown'

  props: ['options', 'selected']

  data: ->
    selection: { active_eq: 1, text: 'Active', show: true }

  methods:
    notify_selection: ->
      @.$emit('update', @.selection)

here is the template

<script id="active-dropdown" type="text/template">
  <div class="form-group">
    <label>Active</label>
    <select class="form-control" v-model="selection" v-on:change="notify_selection">
      <option v-bind:value="{ active_eq: option.value, text: option.text, show: true }" v-for="option in options">{{ option.text }}</option>
    </select>
  </div>
</script>

When I try to use my prop of selected as the select model, vue gives me a warning that I can not mutate props. How I am I suppose to set a default value for the select without changing the model to prop selected?

1 Answer 1

3

Welcome to SO!

Vue doesn't like you to modify a prop directly, instead you pass them to data (or use a computed) and modify that value, which you can do inside the created hook:

props: ['selected','options'],
created(){
  this.selectedOption = this.selected;
},
data(){
  return {
    selectedOption: ''
  }
}

Then you can bind your select box to that:

<select v-model="selectedOption">...</select>

I've created a simplified fiddle to show you how it works:

https://jsfiddle.net/6h8gam1c/

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

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.