我想创建一个包含两个下拉菜单的可重用组件。对于下拉菜单,我使用的是vue-select,我希望能够将两个下拉菜单值绑定到一个变量中。到目前为止,这是我所做的:
ReusableMultiDroddown.vue
<template>
<div class="container">
<div class="row">
<div class="input-group">
<div class="col-md-6">
<v-select
placeholder="Dropdown1"
:options="options1"
:value="value.month"
ref="dd1"
v-model="selected1"
@input="update()"></v-select>
</div>
<div class="col-md-6">
<v-select
placeholder="Dropdown1"
:options="options1"
:value="value.year"
ref="dd2"
v-model="selected2"
@input="update()"></v-select>
</div>
</div>
</div>
</div>
</template>
<script>
import vSelect from 'vue-select';
export default {
props: ['value'],
components: {
'v-select' : vSelect,
},
data() {
return {
selected1: '',
selected2: '',
options1: [
{
label: "one",
value: 1
},
{
label: "two",
value: 2
}
]
}
},
methods: {
update() {
console.log(selected1);
console.log(selected2);
this.$emit('input', {
month: +this.$refs.dd1.value,
year: +this.$refs.dd2.value
})
}
}
}
</script>
我只是无法将'value'的值绑定到主v模型
这是我想在父组件上使用的方式
ParentComponent.vue
<template>
<div class="container">
<rmd v-model="date" ></rmd>
</div>
</template>
<script>
import ReusableMultiDropDown from '../common/ReusableMultiDropDown.vue'
export default {
components: {
'rmd': ReusableMultiDropDown
},
data() {
return {
date: {
month: 1,
year: 2017
}
}
}
}
</script>
因此,无论何时更改两个下拉菜单中的任何一个,我在父组件上的变量也会更改
答案 0 :(得分:3)
我不确定您对这些:value
绑定的处理方式,但是应该在data
属性(即selected1
和selected2
)中发出值因为它们是通过v-model
绑定的。
这是一个例子。我试图简化变量名。
Vue.component('v-select', VueSelect.VueSelect);
Vue.component('rmd', {
template: `<div class="container">
<div class="row">
<div class="input-group">
<div class="col-md-6">
<v-select placeholder="Dropdown1" :options="options" v-model="month" @input="update"></v-select>
</div>
<div class="col-md-6">
<v-select placeholder="Dropdown1" :options="options" v-model="year" @input="update"></v-select>
</div>
</div>
</div>
</div>`,
data() {
return {
month: '',
year: '',
options: [{
label: "one",
value: 1
},
{
label: "two",
value: 2
}
]
}
},
computed: {
monthValue () {
// handle nullable values from v-select
return this.month && this.month.value
},
yearValue () {
// handle nullable values from v-select
return this.year && this.year.value
}
},
methods: {
update () {
this.$emit('input', {
month: this.monthValue,
year: this.yearValue
})
}
}
})
new Vue({
el: '#app',
data: {
date: {month: 1, year: 2017}
}
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<div id="app">
<rmd v-model="date"></rmd>
<pre>{{date}}</pre>
</div>