因项目须要,最近用vue写了个二级联动,刚开始用vue不熟悉,收集了两种方法,这也是我借鉴别人的文章和思路才写出来的,其实没什么区别,能够参考下:
第一种:
这是第一种方法的html部分代码:html
<div id="test"> <select v-model="selected"> <option v-for="yx in YX" :value="yx.text"> {{yx.text}} </option> </select> <select> <option v-for="zy in selection" :value="zy.text" :selected="$index == 0 ? true : false"> {{zy.text}} </option> </select> </div>
这是第一种方法的js部分代码:vue
new Vue({ el: '#test', data: { selected: '计信院', YX: [{ text: '计信院', ZY: [{ text: '软件工程' }, { text: '计算机科学与技术' }, { text: "信息安全" }, ] }, { text: '商学院', ZY: [{ text: '旅游管理' }, { text: '工商管理' }, { text: "行政管理" }, ] }, ] }, computed: { selection: { get: function() { var that = this; return this.YX.filter(function(item) { return item.text == that.selected; })[0].ZY; } } } });
以上是一种方法,整体来讲还不错,并且默认有第一项,无需在写默认项。
下面是另外一种方法,这个方法和上面不一样的是没有默认项,可是比上面哪一种方法更好理解,这个方法怎么加默认项,如今还没搞明白,后续会继续更新:
这是第二种方法的html部分代码:安全
<div id="test"> <select v-model="A"> <option v-for="yx in YX"> {{yx.text}} </option> </select> <select> <option v-for="zy in selection"> {{zy.text}} </option> </select> </div>
这是第二种方法的js部分代码:this
var vm = new Vue({ el:'#test', data:{ YX:[ { text:'计信院', ZY:[ {text:'软件工程'}, {text:'计算机科学与技术'}, {text:"信息安全"}, ] }, { text:'商学院', ZY:[ {text:'旅游管理'}, {text:'工商管理'}, {text:"行政管理"}, ] }, ] }, computed:{ selection: function() { for (var i = 0; i < this.YX.length; i++) { if (this.YX[i].text === this.A) { return this.YX[i].ZY; } } } } });
整体来讲,两种方法均可以,都值得借鉴一下code