使用id
时,我试图在VueJs中获取v-select
值作为选项值。现在,我很难获得将被选择的id
值。有人可以帮我解决这个问题吗?
我的index.html
文件是-
<!DOCTYPE html>
<html>
<head>
<title>VueJs | Select2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
</head>
<body>
<div id="pageContent">
<form method="POST" @submit.prevent="addSection()">
<div class="form-group">
<label for="className">Select Class</label>
<v-select name="className" v-model="className" :options="academicClasses.map(({cname}) => cname)"></v-select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success save-btn"><i class="fa fa-check"></i> Save</button>
</div>
</form>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
</body>
</html>
我的vujs脚本是-
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue({
el: '#pageContent',
data: {
className: '',
academicClasses: [],
academicClasses: [
{
id: 1,
cname: 'One'
},
{
id: 2,
cname: 'Two'
},
{
id: 3,
cname: 'Three'
},
{
id: 4,
cname: 'Four'
}
],
},
methods: {
addSection(){
alert(this.className);
}
}
})
请访问JSFiddle
以获取我要解释的信息!请访问-JsFiddle
答案 0 :(得分:1)
在这里更改:
<v-select name="className" v-model="className" :options="academicClasses.map(academicClass => ({label: academicClass.cname, value: academicClass.id}))"></v-select>
在这里:
alert(this.className.label + ' - ' + this.className.value);
答案 1 :(得分:1)
您要通过以下结构传递options
道具的对象数组:
[{
label: item.cname,
value: item.id
}]
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue({
el: '#pageContent',
data() {
return {
className: '',
academicClasses: [
{ id: 1, cname: 'One'},
{ id: 2, cname: 'Two' },
{ id: 3, cname: 'Three' },
{ id: 4, cname: 'Four' }
],
}
},
methods: {
addSection() {
alert(this.className);
}
},
computed: {
opts() {
return this.academicClasses.map(item => ({
label: item.cname,
value: item.id
}));
}
},
watch: {
className(val) {
console.log(val);
}
}
})
Vue.config.devtools = false;
Vue.config.productionTip = false;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<div id="pageContent">
<form method="POST" @submit.prevent="addSection()">
<div class="form-group">
<label for="className">Select Class</label>
<v-select name="className" v-model="className" :options="opts"></v-select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success save-btn"><i class="fa fa-check"></i> Save</button>
</div>
</form>
</div>