vue.js 组件 component (十三)

组件:组件是可复用的Vue实例,且带有一个名字。

使用 Vue.component函数注册全局组件,第一个参数为组件名。

定义一个组件的示例:

<body>
<div id="app">

	<button-counter @clicknow="clicknow">
		<h2>hi...h2</h2>
	</button-counter>
	
	<button-counter ></button-counter>
</div>
</body>

<script>
//定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
data: function(){
return {
count:0
},
template: '<button @click="count++"> You clicked me {{ count  }}times.</button>
}
}

var vm = new Vue({
	el : "#app",
	data : {
		
	},
	methods:{
		clicknow : function (e) {
			console.log(e);
		}
	}
});
</script>


一个组件包含 属性,数据,模板,方法

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
	
<div id="app">
	<button-counter title="title1 : " @clicknow="clicknow">
		<h2>hi...h2</h2>
	</button-counter>
	<button-counter title="title2 : "></button-counter>
</div>

<script type="text/javascript">
Vue.component('button-counter', {
	props: ['title'],  //组件属性
	data: function () {  //组件的数据
		return {
		  count: 0 
		}
	},
	//组件模板内容, 模板内容需要一个根节点包裹起来
	template: '<div><h1>hi...</h1><button v-on:click="clickfun">{{title}} You clicked me {{ count }} times.</button><slot></slot></div>',
	
	methods:{  //组件方法
		clickfun : function () {
			this.count ++;
			this.$emit('clicknow', this.count);
		}
	}
})
var vm = new Vue({
	el : "#app",
	data : {
		
	},
	methods:{
		clicknow : function (e) {
			console.log(e);
		}
	}
});
</script>
<style type="text/css">

</style>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值