Vue.js 依赖选择 [英] Vue.js dependent select
问题描述
我正处于学习 Vue.js 的初级阶段,遇到了我现在无法弄清楚的问题.所以我有 1 个选择字段:
数据:{列表: {'选项 1': [ { size:'1',prize:'5' }, { size:'2',prize:'10' } ]}}
然后我像这样填充第一个选择字段:
此时一切正常,但是如何根据第一次选择填充另一个选择字段?我需要访问尺寸和价格.
我认为这应该在这里完成:
方法:{onChange:函数(){//获取第二个选择字段的选项}}
我假设在您的数据结构 list
中,每个属性的值定义了您将在第二选择.这里的关键是第一个选择的模型驱动第二个选项.
<option v-for="option in list[firstOption]" value="option.size">{{option.prize}}</option>
我不确定您希望第一次或第二次选择中的文本和值的布局方式,但这里有一个示例.
new Vue({el:"#app",数据: {第一个选项:空,第二个选项:空,列表: {'选项 1': [ { size:'1',prize:'5' }, { size:'2',prize:'10' } ],'选项 2':[{尺寸:'3',奖品:'8'}]}}})
并在您的模板中
<select v-model="firstOption"><option v-for="(item, index) in list">{{ index }}</option></选择><select v-model="secondOption" v-if="firstOption"><option v-for="option in list[firstOption]" value="option.size">{{option.prize}}</option></选择>
I'm in very beginning stage learning Vue.js and encountered problem I can't figure out right now. So I have 1 select field:
data: {
list: {
'Option 1': [ { size:'1',prize:'5' }, { size:'2',prize:'10' } ]
}
}
Then I populating first select field like this:
<select v-model="firstOptions" v-on:change="onChange">
<option v-for="(item, index) in list">{{ index }}</option>
</select>
At this point everything is fine, but how to populate another select field based on first select? I need to access size and price.
I'm think this should be done here:
methods: {
onChange: function() {
// get options for second select field
}
}
I'm assuming here in your data structure, list
, that the value of each property defines the options you will use in the second select. The key here is the model for the first select drives the options for the second.
<option v-for="option in list[firstOption]" value="option.size">{{option.prize}}</option>
I'm not sure how exactly you want your text and values laid out in the first or second selects, but here is an example.
new Vue({
el:"#app",
data: {
firstOption: null,
secondOption: null,
list: {
'Option 1': [ { size:'1',prize:'5' }, { size:'2',prize:'10' } ],
'Option 2': [{size:'3', prize:'8'}]
}
}
})
and in your template
<div id="app">
<select v-model="firstOption">
<option v-for="(item, index) in list">{{ index }}</option>
</select>
<select v-model="secondOption" v-if="firstOption">
<option v-for="option in list[firstOption]" value="option.size">{{option.prize}}</option>
</select>
</div>
这篇关于Vue.js 依赖选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!