vue checkbox 布尔值互转01

vue checkbox 布尔值互转01

note

vue checkbox和数据进行绑定后(v-model),只能对应true、false布尔值类型,checkbox v-model=0 or 1是不可行。所以只能转换了,获取数据填充到checkbox时01->bool,提交数据给后台时bool->01

code

小案例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue lx</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js?a=111"></script>
</head>
<body>
<div id="app">
	<form>
		<ol>
		<li v-for="item in goods"> 
		  <span>{{ item.title }}</span>
		  <input type="checkbox" id="is_new" v-model="item.is_new">
		  <label for="checkbox">{{ item.is_new }}</label>
		  <input type="checkbox" id="is_nb" v-model="item.is_nb">
		  <label for="checkbox">{{ item.is_nb }}</label>
		</li>
	  </ol>
		  <button class="" @click="onSubmit($event)">提交</button>
	</form>
</div>

<script>
new Vue({
	el: '#app',
	data: {
		goods: []
	},
	mounted(){ //html加载完成后执行
		this.inner();
	},
	methods: {
		inner(){ //初始化,填充数据
			//--请求,获取数据
			//this.$http.get('/goods/basic', {
			//}).then((res) => {
			//})
			
			//--获取数据,将01->布尔值
			var tmp_goods = [
				{title:'西瓜',is_new:0,is_nb:1},
				{title:'南瓜',is_new:0,is_nb:1},
				{title:'冬瓜',is_new:0,is_nb:1}
			]
			tmp_goods.forEach(function(item,index){
				tmp_goods[index].is_new = (tmp_goods[index].is_new==1) ? true : false;
				tmp_goods[index].is_nb = (tmp_goods[index].is_nb==1) ?  true : false;
			})
			this.goods = tmp_goods;
		},
		onSubmit(event) {
		  event.preventDefault();//阻止元素发生默认的行为,即阻止表单提交
		  
			//--提交数据,将布尔值->01
		  let data = this.clone(this.goods);
		  for(var index in data){
			data[index].is_new = (data[index].is_new) ? 1 : 0;
			data[index].is_nb = (data[index].is_nb) ?  1 : 0;
		  }
		  console.dir(data);
		},
		clone(myObj) {	//自定义克隆对象方法
			if(typeof(myObj) != 'object') return myObj; 
			if(myObj == null) return myObj; 
			var myNewObj = new Object(); 
			for(var i in myObj) myNewObj[i] = this.clone(myObj[i]); 
			return myNewObj; 
		} 
	}
})
</script>
</body>
</html>
posted @ 2020-07-21 15:16  pine007  阅读(2477)  评论(0编辑  收藏  举报