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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM