vue11 组件初识

组件(component)是vue.js最强大的功能之一。组件的作用就是封装可重用的代码,通常一个组件就是一个功能体,便于在多个地方都能够调用这个功能体。 每个组件都是Vue的实例对象。 我们实例化的Vue对象就是一个组件,而且是所有组件的根组件。

示例代码

        <!DOCTYPE html>
        <html>
        	<head>
        		<meta charset="utf-8" />
        		<title></title>
        		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
        	</head>
        	<body>
        		<div id="app">
					<cow></cow>
					<local1></local1>
        		
        		</div>
				
				<div id="test">
					<cow></cow>
				</div>
        	</body>
        	<script>
			//创建组件
			var mycompoonet=Vue.extend({
				template:"<button @click='count++'>自己加{{count}}全局哦</button>",
				data:function(){
					// data要返回json
					return{count:0}
				}
			})
			Vue.component('cow',mycompoonet);
        	var wm = new Vue({
				el:"#app",
				data:{
					
				},
				components:{
					"local1":{
						template:`<div><div>本地多行</div>
						<div>2</div></div>`
					}
				},
				
			})
			
			var wm = new Vue({
				el:"#test",
				data:{}
			})

        	</script>
        </html>

关键代码

//创建组件
var mycompoonet=Vue.extend({
template:"<button @click='count++'>自己加{{count}}全局哦",
data:function(){
// data要返回json
return{count:0}
}
})
Vue.component('cow',mycompoonet);

实现效果

posted @ 2022-10-12 19:02  冥天肝  阅读(22)  评论(0编辑  收藏  举报