vue 组件 Vue.component 用法

定义:

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

可以在一个通过 new Vue 创建的 Vue 根实例中,把这个组件作为自定义元素来使用

1. 定义一个新组件。命名为 counter

格式:

1.组件名为"conter";

2.data 数据属性:写函数;

3.template 模板:写组件的内容(元素和触发的事件)

Vue.component("counter",{    //1.组件名为"conter"; 2.data 写函数; 3.template 写组件的内容(元素和触发的事件)
	data:function(){
			return {count:0}
			},

//template 是模板的意思,在 html 里面是一个可以同时控制多个子元素的父元素。在这里定义了组件的内容
	template:'<button v-on:click="count++">点击计算点击次数:{{count}}次</button>'
})

 2.在创建的 Vue 根实例中,把这个组件作为自定义元素来使用组件

这里div 元素(faCounter)就是vue 实例的根元素。

组件counter 被作为自定义元素,嵌套在根元素 faCounter 里面

<div id="faCounter">  <!--faCounter 就是组件元素counter的父元素,要把新建的vue实例绑定在这个父元素-->
<counter></counter>   <!--counter 就是新建的组件,也就是自定义的元素-->
</div>
new Vue({
     el:"#faCounter"
    })

网页效果:

完整代码:

<div id="faCounter">  <!--faCounter 就是组件元素counter的父元素,要把新建的vue实例绑定在这个父元素-->
<counter></counter>   <!--counter 就是新建的组件,也就是自定义的元素-->
</div>

<script> 
//定义一个新的vue 组件。组件就是自定义的元素
Vue.component("counter",{    //1.组件名为"conter"; 2.data 写函数; 3.template 写组件的内容(元素和触发的事件)
	data:function(){
			return {count:0}
			},

//template 是模板的意思,在 html 里面是一个可以同时控制多个子元素的父元素。在这里定义了组件的内容
	template:'<button v-on:click="count++">点击计算点击次数:{{count}}次</button>'
})

//定义一个新的vue  实例,用el 绑定组件元素(counter)的父元素  faCounter 元素上
new Vue({
	el:"#faCounter"
	})

</script>

 


猜你喜欢

转载自blog.csdn.net/weixin_41796631/article/details/82929139