foreword
The drop-down box is very common for development, and it is also a common component in interface design. In some usage scenarios, we need to make the drop-down box selectable and at the same time support search and input. Take the drop-down box component of element as an example , when we set the property to support search and input at the same time, the following problem will appear:
From the animation above, it is not difficult to see that it is no problem to enter an existing value in the drop-down box for matching. Clicking Submit will also print out the value in the console, but when we enter a value that does not exist, click Submit again. The console does not print out, why is this?
Analyze the reasons
The main reason is that when vue
developing , a certain value in the page is changed in the function, and the modification is successful when viewed in the function, but the changed value is not refreshed in time on the page.
solution
this.$forceUpdate()
this.Sforceupdate()
Is one vue
of api
, it can force the component to update, that is, when the data of the component changes, it can immediately update the view of the component without waiting for the next re-render.
The this.$forceupdate() function has the following characteristics:
- It can force the component to update. When the data changes, the view of the component is updated immediately without waiting for the next re-render;
- It can avoid component re-rendering and improve performance;
- It can avoid unpredictability in some cases
bug
; - It keeps components consistent across different environments.
In addition, this.$forceupdate()
the function can also accept a parameter, the parameter is of boolean
type , passing true
in can force the update of the sub-component, false
when , only the current component itself will be updated.
adjusted
full code
<template>
<div class="parentBox">
<el-select v-model="foodModel" placeholder="请选择" clearable filterable @blur="selectBlur" @clear="selectClear">
<el-option v-for="item in options" :key="item.index" :label="item.label" :value="item.value"></el-option>
</el-select>
<el-button type="primary" @click="submitOn">提交</el-button>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{
value: "0",
label: "黄金糕",
},
{
value: "1",
label: "双皮奶",
},
{
value: "2",
label: "蚵仔煎",
},
{
value: "3",
label: "龙须面",
},
{
value: "4",
label: "北京烤鸭",
},
],
foodModel: "",
};
},
methods: {
selectBlur(e) {
this.foodModel = e.target.value;
this.$forceUpdate(); // 强制更新
},
selectClear() {
this.foodModel = "";
this.$forceUpdate(); // 强制更新
},
// 模拟提交
submitOn() {
console.log(this.foodModel);
},
},
};
</script>
expand
After solving
input
the label settingtype="number"
,maxlength
the problem of invalidation.
Add oninput
an event , use js
to judge, if the length is greater than the set number of digits, it will be intercepted.
<el-input oninput="if(value.length > 6) value = value.slice(0,6)" v-model="value" type="number"></el-input>