【发布时间】:2021-11-15 15:45:12
【问题描述】:
我有两个组件,一个输入和一个选择,选择显示选项取决于您在输入中写入的内容,但如果所选选项未显示在新选项中,请选择默认选项或第一个选项“选择选项”
当我选择一个选项然后更改 Select 中的选项并且所选选项不在新选项中时,Select 显示为空白,但是当我将所选选项更改为“”时,Select 不会更改到它(选择具有值“”的选项),我不知道为什么,但是如果我更改为其他选项,则选择会更改为它...
示例:
选择选项 2 > 在输入中写入 3 个字符
您可以看到变量option_selected 与选择更改为“”绑定,但选择不会更改为“选择选项”
此示例的文档链接:
Component custom events
const input_text = {
name: "input-min-length",
props: {
text: String,
is_min_length: Boolean
},
emits: ["update:text", "update:is_min_length"],
computed: {
is_min(){
return this.text.length >= 3;
}
},
watch: {
is_min(new_value){
this.$emit("update:is_min_length", this.is_min);
}
},
template: `<div><input type="text" :value="text" @input="$emit('update:text', $event.target.value)" /></div>`
};
const select_options = {
name: "select-options",
props: {
option_selected: String,
is_min_length: Boolean
},
emits: ["update:option_selected"],
data() {
return {
options: [
{text: "Select option", value: ""},
{text: "option 1", value: "1", is_min_length: true},
{text: "option 2", value: "2"},
{text: "option 3", value: "3", is_min_length: true},
]
};
},
computed: {
options_filtered(){
if(this.is_min_length == false) return this.options;
return this.options.filter((option) => option.is_min_length == true || option.value == "")
}
},
watch: {
is_min_length(){
const is_presented = this.options_filtered.some((option) => option.value == this.option_selected)
if (is_presented == false){
setTimeout(() => {
this.$emit("update:option_selected", "");
}, 0); // I try to use setTimeout, to see if it changes at all
}
}
},
template: `
<select :value="option_selected" @change="$emit('update:option_selected', $event.target.value)">
<option v-for="option in options_filtered" :value="option.value" :key="option.value">
{{ option.text }}
</option>
</select>
`
}
const app = {
components:{
"input-min-length": input_text,
"select-options": select_options
},
data() {
return {
text: "",
is_min_length: false,
option_selected: ""
}
},
template: `
<div>
<input-min-length v-model:text="text" v-model:is_min_length="is_min_length" />
<select-options v-model:option_selected="option_selected" :is_min_length="is_min_length" /><br>
<button @click="option_selected='1'">change to opt 1</button><br>
<button @click="option_selected=''">change to opt ""</button><br>
<div>
<strong>DATA:</strong><br>
<strong>text:</strong> "{{text}}"<br>
<strong>is_min_length:</strong> {{is_min_length}}<br>
<strong>option_selected:</strong> "{{option_selected}}"
</div>
</div>`
}
Vue.createApp(app)
.mount('#app')
<script src="https://unpkg.com/vue@next"></script>
<div id="app"></div>
【问题讨论】:
标签: vue.js select input binding vue-component