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>

运行结果如下所示:

各个组件之间数据互不影响。

猜你喜欢

转载自blog.csdn.net/cattleya_ada/article/details/82983409