项目中使用到开始月份与结束月份,为了适应结束月份必须大于等于开始月份,使用动态赋值的方式,当选择开始月份的时候,动态添加结束月份,于是在最外层定义一个数组,动态的往里面添加数据进行赋值,我使用的是vue的方法,大家可以参考

一、页面部分代码如下

<div class="input-group input-group-sm mb-3" style="margin-top: -10px;">
   <div class="input-group-prepend">
      <span class="input-group-text" style="width: 79px;"><span style="width: 100%;">开始月份</span></span>
   </div>
   <select v-select2="" id="beginMonth" v-model="beginMonth" v-on:change="getChange(beginMonth)" data-placeholder="请选择开始月份"  class="js-example-placeholder-multiple col-sm-12">
        <option value="">请选择...</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="0">0</option>
        <option value="11">11</option>
        <option value="12">12</option>
    </select>
        <span></span>
    </div>
    <div class="input-group input-group-sm mb-3" style="margin-top: -10px;">
        <div class="input-group-prepend">
            <span class="input-group-text" style="width: 79px;"><span style="width: 100%;">结束月份</span></span>
        </div>
        <select v-select2="" id="endMonth" v-model="endMonth" data-placeholder="请选择结束月份"  class="js-example-placeholder-multiple col-sm-12">
            <option value="">请选择...</option>
            <option v-for="data in varEndMonthList" :value="data.id">{{data.name}}</option>
        </select>
        <span></span>
    </div>

二、js代码如下

//vue下动态监听到select2值的变化
Vue.directive('select2', {
	inserted: function (el, binding, vnode) {
		let options = binding.value || {};

		$(el).select2(options).on("select2:select", (e) => {
			el.dispatchEvent(new Event('change', {target: e.target})); //说好的双向绑定,竟然不安套路
		});
	},
	update: function (el, binding, vnode) {
		for (var i = 0; i < vnode.data.directives.length; i++) {
			if (vnode.data.directives[i].name == "model") {
				$(el).val(vnode.data.directives[i].value);
			}
		}
		$(el).trigger("change");

	}
});

var vm = new Vue({
	el: '#app',
	data:{
		pd: {beginMonth: ''},
		varEndMonthList: []
	},
	methods: {
		getChange: function (beginMonth) {
			let endStr = '';
			for (var i = beginMonth; i <= 12 ; i++) {
				endStr = {id: i , name: i};
				this.varEndMonthList.push(endStr);
			}
		},
})

此处主要用到的是定义数组往里面添加json数据

//主要知识点如下
varEndMonthList: [],
for (var i = beginMonth; i <= 12 ; i++) {
	let endStr = {id: i , name: i};
	this.varEndMonthList.push(endStr);
}
Logo

前往低代码交流专区

更多推荐