vuejs 三级联动

最近在学习vuejs,写了一个城市三级联动效果,可以用在项目中的收获地址管理,支持新增与修改操作

HTML


JavaScript


var addressExtend=Vue.extend({
	template:"#address-template",
	props:{
		province:{
			type:String,
			default:''
		},
		city:{
			type:String,
			default:''
		},
		county:{
			type:String,
			default:''
		}
	},
	data:function(){
		return {
			addressData:null
		}
	},
	init:function(){
		var that=this
		setTimeout(function(){
			that.addressData={
				'湖南':{
					'长沙':{
						"开福区":{},
						"岳麓区":{}
					},
					'怀化':{
						'沅陵':{},
						'溆浦':{}
					}
				},
				'广东':{
					'广州':{
						'天河区':{},
						'越秀区':{}
					},
					'深圳':{
						'宝安':{},
						'南山':{}
					}
				}
			}
		},1000)
	},
	watch:{
		province:function(val,oldval){
			if(val!==oldval){
				this.city=''
			}
		},
		city:function(val,oldval){
			if(val!==oldval){
				this.county=''
			}
		}
	},
	computed:{
		provinces:function(){
			if(!this.addressData)return

			var c=[]
			for(var key in this.addressData){
				c.push(key)
			}

			return c
		},
		citys:function(){
			if(!this.addressData 
				|| !this.province)
				return 

			var c=[]
			for(var key in this.addressData[this.province]){
				c.push(key)
			}

			return c
		},
		countys:function(){
			if(!this.addressData
				||!this.city)
				return

			var c=[]
			for(var key in this.addressData[this.province][this.city]){
				c.push(key)
			}

			return c
		}
	}
})

Vue.component('address',addressExtend)

var demo1=new Vue({
	el:'#demo',
	data:{
		province:'广东',
		city:'广州',
		county:'天河区'
	}
})

去jsfiddle手动试试
此文同步发表于Segmentfault

你可能感兴趣的:(vuejs 三级联动)