【发布时间】:2018-10-25 06:39:00
【问题描述】:
我正在尝试记住如何从组件中返回选择中的值。
尽管我打赌很容易我忘记了,或者我只是做错了。
我调用组件:
<custom-select :options="options" v-model="selectedMain"></custom-select>
然后我有组件本身:
<template>
<fieldset class="form-group">
<select v-model="selected"
id="something"
name="something">
<option :value="null">Select an option</option>
<option v-for="option in options"
value="option.id"
v-html="option.name"></option>
</select>
</fieldset>
</template>
<script>
module.exports = {
props: [ 'options' ],
data: function() {
return {
selected: null
}
}
}
</script>
这当然是在我的主 Vue 实例中定义的,并且呈现正常:
new Vue({
...
data: function() {
return {
...
selectedMain: null
...
}
},
...
})
但是,当我从下拉列表中将值更改为 1(例如)时,我可以在 Vue 调试器工具栏中看到:
<Root> selectedMain: null <CustomSelect> selected: 1 </CustomSelect> </Root>
编辑 1:我认为这几乎是一回事:
Vue.component('custom-select', {
data () {
return {
selected: null
}
},
props: [ 'options' ],
template: `<fieldset class="form-group">
<select v-model="selected"
id="something"
name="something">
<option :value="null">Select an option</option>
<option v-for="option in options"
value="option.id"
v-html="option.name"></option>
</select>
</fieldset>`
});
new Vue({
el: '#app',
data: function() {
return {
options: [
{ id: 1, name: "First option" },
{ id: 2, name: "Second option" },
{ id: 3, name: "Third option" },
],
selectedMain: null
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<custom-select :options="options" v-model="selectedMain"></custom-select>
<p>Selected Main: {{ selectedMain }}</p>
</div>
因此,我显然希望 selectedMain 采用 selected 值。
如何做到这一点?任何建议表示赞赏。
【问题讨论】:
标签: javascript laravel vue.js vuejs2 vue-component