基于Vue的三级联动下拉框

该博客介绍了如何使用Vue.js实现三级联动下拉框的功能。在HTML部分,讲解了设置和获取select值、显示option列表及设置option属性的方法。在JavaScript部分,详细阐述了在Vue实例中定义相关变量、初始化操作以及监听Unit和Department下拉框变化以动态更新列表的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

展示

width="100%" height="300" src="//jsfiddle.net/3gqrmbum/embedded/" allowfullscreen="allowfullscreen">

html部分

  1. 使用v-model设置和获取select的值
  2. 使用v-for显示option列表
  3. 使用:value设置option属性
  4. 使用{{}}输出内容
<div id="test">
    单位:
    <select v-model="UnitSelected">
        <option v-for="item in UnitList" :value="item.id">{{item.name}}</option>
    </select>
    部门:
    <select v-model="DepartmentSelected">
        <option v-for="item in DepartmentList" :value="item.id">{{item.name}}</option>
    </select>
    用户:
    <select v-model="UserSelected">
        <option v-for="item in UserList" :value="item.id">{{item.name}}</option>
    </select>
</div>

JavaScript部分

  1. data中定义vue相关变量
  2. created中完成初始化变量的操作
  3. watch中监听Unit和Department下拉框的编号,并更新列表
var UnitRows = [
    {name:"1",id:"1"},
    {name:"2",id:"2"},
];
var DepartmentRows = [
    {name:"11",id:"1",pid:"1"},
    {name:"12",id:"2",pid:"1"},
    {name:"21",id:"3",pid:"2"},
    {name:"22",id:"4",pid:"2"}
];
var UserRows = [
    {name:"111",id:"1",pid:"1"},
    {name:"112",id:"2",pid:"1"},
    {name:"121",id:"3",pid:"2"},
    {name:"122",id:"4",pid:"2"},
    {name:"211",id:"5",pid:"3"},
    {name:"212",id:"6",pid:"3"},
    {name:"221",id:"7",pid:"4"},
    {name:"222",id:"8",pid:"4"}
]
var vm = new Vue({
    el:"#test",
    data:{
        UnitSelected:"",
        UnitList:[],
        DepartmentSelected:"",
        DepartmentList:[],
        UserSelected:"",
        UserList:[]
    },
    created:function () {
        this.UnitList = UnitRows;
        this.UnitSelected = this.UnitList.length>0 ? this.UnitList[0].id : "";

        var val = this.UnitSelected;
        this.DepartmentList = DepartmentRows.filter(function (x) { return x.pid == val });
        this.DepartmentSelected = this.DepartmentList.length>0 ? this.DepartmentList[0].id : "";

        val = this.DepartmentSelected;
        this.UserList = UserRows.filter(function (x){ return x.pid == val});
        this.UserSelected = this.UserList.length>0 ? this.UserList[0].id : "";
    },
    watch:{
        UnitSelected:function (val) {
            this.DepartmentList = DepartmentRows.filter(function (x) { return x.pid == val });
            this.DepartmentSelected = this.DepartmentList.length>0 ? this.DepartmentList[0].id : "";
        },
        DepartmentSelected:function (val) {
            this.UserList = UserRows.filter(function (x){ return x.pid == val});
            this.UserSelected = this.UserList.length>0 ? this.UserList[0].id : "";
        }
    }
});
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值