组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。我们经常会自定义很多组件以满足我们不同的需求。
一.自定义全局组件
方法1.
全局组件用到的是 Vue.component(tagName,option),tagName是自定义的组件名称,option是组件构造器。具体使用方法如下:
在main.js中设置:
Vue.component('my-component', {
template: '<button v-on:click="clickShow">切换<h1 v-show="show">全局组件的学习</h1></button>',
data () {
return {
show: true
}
},
methods:{
clickShow(){
this.show = !this.show
}
}
})
在组件中直接引用:
<template>
<div>
<my-component ></my-component>
</div>
</template>
渲染结果为:
image
方法2.
Vue.extend(options) Vue.extend返回的是一个“扩展实例构造器”,不是具体的组件实例,也就是预设了部分选项的Vue的实例构造器,它常常服务于Vue.component用来生成组件,可以简单理解为当在模板中遇到该组件作为标签的自定义元素时,会自动调用“扩展实例构造器”来生产组件实例,并挂在到自定义元素上.
在main.js中设置:
var Profile = Vue.extend({
template: '<button v-on:click="show=!show">切换<h1 v-show="show">全局组件的学习</h1></button>',
data: function () {
return {
show: true
}
}
})
Vue.component('my-component',Profile)
//Vue.component 是用来全局注册组件的方法,其作用是将通过 Vue.extend 生成的扩展实例构造器注册(命名)为一个组件
同上直接引用,渲染结果同上。
注:**data
** 在 Vue.extend()
**中它必须是**函数
**。**
二.局部组件使用
template>
<div>
<button v-on:click="show=!show">切换
<h1 v-show="show">全局组件的学习</h1>
</button>
</div>
</template>
components: {
'my-component': MyComponent
},
<template>
<div>
<MyComponent></MyComponent>
</div>
</template>
注: 组件内容过多情况下使用局部组件使代码更加清晰明了!
使用组件容易遇到问题:https://cloud.tencent.com/developer/article/1393996
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有