2
votes

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

1 Answers

3
votes

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/