我是 vue.js 的新手,正在尝试为我的选择框创建一个组件。我很难想通过父组件将默认值传递给选择。
现在我在父组件中有这个
<div class="row">
<div class="col-md-4">
<active-dropdown :selected='selected', :options = 'active_options', @update = 'update_selected'></active>
</div>
</div>
这是下拉组件
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)
这是模板
<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>
当我尝试使用 selected 的 props 作为选择模型时,vue 会警告我不能改变 props。我该如何为选择设置默认值而不将模型更改为 Prop 选择?
最佳答案
欢迎来到SO!
Vue 不喜欢您直接修改 prop
,而是将它们传递给数据(或使用计算值)并修改该值,您可以在创建的 Hook 内执行此操作:
props: ['selected','options'],
created(){
this.selectedOption = this.selected;
},
data(){
return {
selectedOption: ''
}
}
然后您可以将选择框绑定(bind)到它:
<select v-model="selectedOption">...</select>
我创建了一个简化的 fiddle 来向您展示它是如何工作的:
关于javascript - 选择组件Vue JS - 默认选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40310858/