本文已参与[新人创作礼]活动, 一起开启掘金创作之路。
前言
众所周知,现今企业中的前端开发,不是光会大学里的HTML、CSS、JavaScript就可以上手的。前端早已跨过了刀耕火种的时代,各种框架层出不穷,打开招聘网站,月薪三千块的岗位都要求会Vue。因此要想吃上前端开发这口饭,就至少得学会Vue.js。 本文梳理Vue组件的使用,乃Vue学习的第二大关。 使用组件的好处:组件能实现复杂的页面结构,提高代码的可复用性,减少重复代码的编写,提高开发效率,降低代码之间的耦合度,使得项目更易于维护和管理。
提示:以下是本篇文章正文内容,下面案例可供参考
全局组件:
一、全局组件-注册方法1-远古秘方
使用到:Vue.extend、Vue.component、template。
1.调用Vue.extend方法,传入目标格式对象
代码如下(示例):
const cpn1 = Vue.extend({
template:`
<div>
<h2>我是组件cpn1</h2>
<button v-on:click="count++">被单击{{count}}次</button>
</div>
`,
data() {
return {
count: 0,
};
},
});
注意:data必须是一个方法,并且用return返回数据。:
2.调用Vue.component,注册全局组件
代码如下(示例):
Vue.component("cpn1",cpn1);
运行结果如下(示例):
至此,一个全局组件已经注册成功。(注:该注册方法过于古老,现今官方文档和各种资料都使用一种全新的语法糖简约注册)
二、全局组件-注册方法2-语法糖秘方
使用到:Vue.component、template。
1.直接调用Vue.component方法,传入Vue.extend参数所需格式的对象,完成组件注册
代码如下(示例):
Vue.component('my-component',{
data() {
return {
count: 0,
};
},
template: `
<div>
<h2>我是组件cpn1</h2>
<button v-on:click="count++">被单击{{count}}次</button>
</div>
`,
});
运行结果如下(示例):
使用改方法,直接省略调用Vue.extend步骤,但其实内部还是会调用Vue.extend来实现。 使用该方法,一步到位,十分方便,但是代码依旧不够简洁,我们接着看下去。
三、全局组件-注册方法3-template标签-以及远古秘方与语法糖糅合
使用到:Vue.component、template标签。
1.在html标签中定义template
代码如下(示例):
<template id="cpn3">
<div>
<h2>我是全局组件cpn3</h2>
<button v-on:click="count++">被单击{{count}}次</button>
</div>
</template>
随后 可以在js中通过id找到该模板。好处:使用该标签非常方便书写html标签。(注意:template标签中需要用一个div作为根将标签包裹起来)
使用到:Vue.component、template。
2.简约定义Vue.extend对象,调用Vue.component完成注册
由于在Vue.component中直接书写对象使得代码复杂不具备可读性,因此事先将对象在外先定义好在传进去,代码如下(示例):
const cpn3={
template:'#cpn3',
data() {
return {
count: 0,
};
}
}
Vue.component('cpn3',cpn3);
运行结果如下(示例):
使用该方法,既方便template模板的书写,又省去了Vue.extend的调用。保证了代码的美观,可阅读性。
四、 全局组件总结:
1、template模板在html中用template标签定义好。 2、Vue.extend写起来麻烦,直接用语法糖解决,即直接在js代码中定义格式一样的对象。 3、最终全局注册都调用Vue.component方法。
局部组件:
一、局部组件-注册方法-粗鲁-Vue实例中的component直接传Vue.extend对象
使用到:component、template。
1.添加component对象,传入Vue.extend格式的对象
代码如下(示例):
const app=new Vue({
el:'#app',
data: {
message:"hello Vue"
},
methods:{},
components:{
cpn1:{
template:`
<div>
<h2>我是局部组件cpn1</h2>
<button v-on:click="count++">被单击{{count}}次</button>
</div>
`,
data() {
return {
count: 0,
};
},
}
}
})
注意:data必须是一个方法,并且用return返回数据。:
一、局部组件-注册方法2-精细-Vue.extend对象的数据事先定义好再传
使用到:component、template。
1.外部制作好Vue.extend参数所需格式对象,然后传入实例中的component中
代码如下(示例):
const cpn2={
template:`
<div>
<h2>我是局部组件cpn2</h2>
<button v-on:click="count++">被单击{{count}}次</button>
</div>
`,
data() {
return {
count: 0,
};
},
}
const app=new Vue({
el:'#app',
data: {
message:"hello Vue"
},
methods:{},
components:{
cpn2:cpn2
}
})
总结
组件注册都用到component方法,该方法里面包含template、data。其中template可以用template标签写,然后利用id引用;而data必须是一个函数,函数用return返回数据。 细节的人事先定义好Vue.extend()参数所需格式对象,然后再给到component。此乃金针菇前端汪。 全局组件和局部组件的区别在于:全局调用Vue.component,而局部调用的是Vue实例中的component