1. 程式人生 > >vue.js For迴圈,vue.js v-for使用

vue.js For迴圈,vue.js v-for使用

vue.js For迴圈,vue.js v-for使用

 

================================

©Copyright 蕃薯耀 2018年11月28日

http://fanshuyao.iteye.com/

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>vue For迴圈</title>
</head>
<body>
	
	<div id="forDiv">
		<ul>
			<li v-for="obj in persons">{{obj.name}}[{{obj.age}}]</li>
		</ul>

		<ul>
			<li v-for="(obj, index) in persons">
				{{index}}、{{obj.name}}[{{obj.age}}]
				----<input type="button" @click="deleteBy(index)" value="刪除"/>
				----<input type="button" @click="updateBy(index, index)" value="屬性更新"/>
				----<input type="button" @click="updateByObj(index)" value="物件更新"/>
			</li>
		</ul>
	</div>

<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
var app = new Vue({
	el: "#forDiv",
	data: {
		persons: [
			{name: "張三", age : 18},
			{name: "李四", age : 19},
			{name: "王五", age : 17}
		]
	},
	methods: {
		deleteBy : function(index){
			//splice() 方法從陣列中新增/刪除專案,然後返回被刪除的專案。
			//arrayObject.splice(index,howmany,item1,.....,itemX)
			//index: 必需。整數,規定新增/刪除專案的位置,使用負數可從陣列結尾處規定位置。
			//howmany : 必需。要刪除的專案數量。如果設定為 0,則不會刪除專案。
			//item1,.....,itemX : 可選。向陣列新增的新專案。
			this.persons.splice(index, 1);
		},
		updateBy : function(index, index){
			this.persons[index].name=this.persons[index].name + index + "";

		},
		updateByObj : function(index){
			//this.persons[index] = {name: '馬六', age : 20};//這樣不能直接改變頁面顯示的值
			this.persons.splice(index, 1, {name: '馬六', age : 20});//這樣使用
			
			
			//Vue 包含一組觀察陣列的變異方法,所以它們也將會觸發檢視更新。這些方法如下: 
			//push() 向陣列的末尾新增一個或更多元素,並返回新的長度。
			//pop() 刪除並返回陣列的最後一個元素
			//shift() 	刪除並返回陣列的第一個元素
			//unshift() 向陣列的開頭新增一個或更多元素,並返回新的長度。
			//splice() 刪除元素,並向陣列新增新元素。
			//sort() 對陣列的元素進行排序
			//reverse() 顛倒陣列中元素的順序。
		}
	}
});
</script>
</body>
</html>

 

================================

©Copyright 蕃薯耀 2018年11月28日

http://fanshuyao.iteye.com/