1. 程式人生 > >Vue.js之元件data的使用

Vue.js之元件data的使用

官網連結:https://cn.vuejs.org/v2/guide/components.html

參考連結:http://www.cnblogs.com/keepfool/p/5625583.html

教學視訊參考連結:

https://ke.qq.com/webcourse/index.html#cid=320654&term_id=100380571&taid=2520179435431054&vid=t1428m0ykhd

傳入Vue構造器的多數選項也可以用在Vue.extend()或Vue.component()中。

Vue.js規定:在定義data選項時,必須使用函式

如果data選項指向某一個物件,這意味著所有的元件例項公用一個data。如下程式碼所示:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title></title>
	<link rel="stylesheet" href="">
	<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<body>
   <div id="app">
	   	<my-com1></my-com1>	
	   	<my-com1></my-com1>	
	   	<my-com1></my-com1>	
	   	<my-com1></my-com1>	
   </div>
   <div id="app1"></div>
	<script>
	let data={
		count:0
	}
	Vue.component('myCom1',{
		template:"<h3 @click='count++'>這是元件哦~{{count}}</h3>",
		data:function(){
			return data
		}
	});
	var vm=new Vue({
		el:'#app'

	})
		new Vue({
		el:'#app1',
		template:'<my-com1></my-com1>'

	})

	</script>
</body>
</body>
</html>

執行結果如下所示:

點選任意一個元件,其它元件的資料都會發生變化。

因此,我們應當使用一個函式作為data選項,讓這個函式返回一個新物件:

Vue.component('my-component', {
	data: function(){
		return {a : 1}
	}
})

如下程式碼所示:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title></title>
	<link rel="stylesheet" href="">
	<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<body>
   <div id="app">
	   	<my-com1></my-com1>	
	   	<my-com1></my-com1>	
	   	<my-com1></my-com1>	
	   	<my-com1></my-com1>	
   </div>
   <div id="app1"></div>
	<script>
		let data={
			count:0
		}
		Vue.component('myCom1',{
			template:"<h3 @click='count++'>這是元件哦~{{count}}</h3>",
			data:function(){
				return {
					count:0
				}
			}
		});
		var vm=new Vue({
			el:'#app'

		})
		new Vue({
			el:'#app1',
			template:'<my-com1></my-com1>'

	})

	</script>
</body>
</body>
</html>

執行結果如下所示:

各個元件之間資料互不影響。