vue.js - 如何从动态填充的选择框中侦听初始更改事件
问题描述
由于 HTTP 请求,我在 Vue.js 中有一个动态填充的选择框。我正在监听@change
事件以运行一些程序代码,但是该事件仅在用户进行更改@change
时触发。它不会捕获填充选择框并选择值时发生的初始事件。
这是我的代码:
const app = Vue.createApp({
methods: {
handleSelectSize(size) {
console.log('handleSelectSize', size.target.value);
const sizeLabels = {
'S': 'small',
'M': 'medium',
'L': 'large'
};
this.label = sizeLabels[size.target.value];
}
},
data() {
return {
selectedSize: 'M',
label: '',
sizeOptions: null
}
},
mounted() {
window.setTimeout(() => {
// Dynamically create values for dropdown
this.sizeOptions = ['S', 'M', 'L'];
}, 500);
}
});
app.mount('#myApp');
<script src="https://unpkg.com/vue@next" ></script>
<div id="myApp">
<label>Select Size
<select v-model="selectedSize" @change="handleSelectSize($event)">
<option v-for="size in sizeOptions" v-bind:value="size">
{{ size }}
</option>
</select>
</label>
<div>
The current size is {{label}}
</div>
</div>
选择组件上有一个@change
处理程序,用于更新.label
属性。该.label
属性用于输出文本:“当前大小为 {{label}}”。
问题是第一次填充@change
选择框时不会触发。如果您手动更改它,它可以正常工作。
我怎样才能捕捉到选择框上的初始变化?
解决方案
原因是,的价值selectedSize
没有改变,只有选项。我会建议为标签使用计算,这样你就可以省略@change
事件
data(){
return {
selectedSize: 'M',
sizeLabels = {
'S': 'small',
'M': 'medium',
'L': 'large'
},
selectedOptions: [] // better initialized this with array
}
},
computed:{
label(){
return this.selectedOptions.length ?
this.selectedOptions[this.selectedSize] // please handle also if key can not be found
: ''
}
}
最好也为每个选项获得标签
window.setTimeout(() => {
// Dynamically create values for dropdown
this.sizeOptions = [{label: 'foo', 'value': 'bar'}, etc];
}, 500);
推荐阅读
- reactjs - 如何在反应应用程序中设置我的 index.tsx 文件的路径?
- discord.js - TypeError:无法读取未定义的属性“消息”
- python - 用python插入
- sql - SQL(SQL/Oracle) 从 select 语句中插入值
- reactjs - 为什么 typescript 不能确保在 React 中添加额外属性的通用高阶组件中的类型安全?
- node.js - 有没有办法在 node_modules 中本地“预安装”模块?n
- android-studio - Android Studio 4.1 Kotlin 小部件 ID 在 AminActivity.kt 中无法识别
- mysql - SQL 初学者 - 如何检索最年轻的检测呈阳性的患者?
- javascript - 每次在反应中加载组件时,如何调用 $().dropdown 函数?
- r - 如何创建混淆矩阵并确定 R 中 50% 截止的效果?