<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="components-demo">
<!-- 我们可以在一个通过new Vue创建的Vue根实例中,把这个组件作为自定义元素来使用 -->
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
<!-- 我们可以将组件进行任意次的复用 -->
<!-- 注意当点击按钮时,每个组件都会各自独立维护它的count,因为每用一次组件,就会有一个它的新实例被创建 -->
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
<script>
// 定义一个名为 button-counter 的新组件,组件是可复用的Vue实例
// 因为组件是可复用的Vue实例,所以他们与new Vue接受相同的选项,例如data、computed、watch、methods以及生命周期钩子等,
// 唯一不同的是没有el这样根实例特有的选项
// Vue.component 这种方式是全局注册,全局注册的组件可以用在其被注册之后的任何(通过new Vue)新创建的Vue根实例,也包括子组件模板中
// 组件的命名上,短横线和驼峰命名都可以,但是在混搭不独立文件的时候,只能用短横线的方式命名
Vue.component('button-counter', {
// 一个组件的data选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝
data: function () {
return {
count: 0
}
},
template: `<button v-on:click="change">You clicked me {{ count }} times.</button>`,
methods:{
change:function() {
this.count++
}
}
})
var app = new Vue({
el: '#components-demo'
})
</script>
</body>
</html>
Vue自定义全局组件
最新推荐文章于 2024-04-01 21:53:13 发布