
开篇寄语
继续深化学习Vue.js这个Web框架的相关内容,之前的一些基础内容可以参看下方的前情提要,本篇文章主要是来介绍一下Vue-cli搭建的项目,如何注册全局或局部使用的组件,其实很简单,那就是按照以下步骤即可达成……
前情提要
- 《科学入门Vuejs,几个小示例让你爱上它》
- 《Vuejs中各种"v-xxx"都是什么,一篇带示例的文章让你搞清楚》
- 《Vuejs中的methods, computed和watch有何妙用?》
- 《Vuejs中组件开发从初级到高级(一)》
- 《Vuejs中组件开发从初级到高级(二)》
- 《Vue.js中Vue Router该如何掌握?本篇文章来说清楚》
内容详情
本篇以Vue3版本为例,虽然与Vue2差别并不是很大。
这里,伯衡君引入了一个名为v3-carousel的轮播图开源依赖库充当组件,读者可不必安装,只需要领略如何注册组件和引用组件即可。
伯衡君喜欢把组件都放在Vue-cli项目的components文件夹下面,新建了一个名为library的文件夹,之后就新建了一个名为carsouler.vue的文件,内容如下:
<template>
<div class="home">
<Carousel
:autoplay="true"
:duration="3000"
:initIndex="2"
:direction="true"
directionMode="hover"
:directionSize="20"
directionColor="skyblue"
:indicator="true"
indicatorMode="always"
indicatorColor="white"
indicatorActiveColor="skyblue"
@before-moving="beforeMoving"
@after-moving="afterMoving"
>
<CarouselItem
v-for="(item, index) in data"
:key="index"
:idx="index"
@click="greet(index)"
>
<img :src="item" />
</CarouselItem>
</Carousel>
</div>
</template>
<style>
.home {
width: 100%;
height: 300px;
}
</style>
<script>
import { defineComponent, reactive, toRefs } from "vue";
export default defineComponent({
name: "carsouler",
methods: {
greet(event) {
if (event == 0) {
window.open("https://google.com");
}
},
},
setup() {
const state = reactive({
data: [
"https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00693-2745.jpg",
"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2190440116,1436403087&fm=26&gp=0.jpg",
"https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3593656793,3600757928&fm=26&gp=0.jpg",
],
});
function beforeMoving(dire) {
console.log("before", dire);
}
function afterMoving(obj) {
console.log("after", obj);
}
return {
...toRefs(state),
beforeMoving,
afterMoving,
};
},
});
</script>
该组件的名称就命名为carsouler了,后面会用到,如果想全局引用,只需要到main.js内这样书写:
import { createApp } from 'vue'
import Carousel from "v3-carousel";
import App from './App.vue'
//import css
import 'element3/lib/theme-chalk/index.css'
import Element3 from 'element3'
import router from './router'
import Carsouler from './components/library/carsouler.vue'//主要是这个
// global import
createApp(App).use(router).use(Element3).use(Carousel).component(Carsouler.name, Carsouler).mount('#app')//以及component选项里的填充内容
之后,就可以随时调用该组件了,比如伯衡君就在job.vue(自定义使用名称)调用该组件,代码如下:
<template>
<div class="job">
<p>This is an about page</p>
</div>
<carsouler></carsouler>
</template>
生成效果如下图所示:

全局引用实现了,那么接下来就是局部引用,其实道理类似,只需要这样操作,比如想在Computer.vue内应用该组件,只需要先将该组件在<script></script>引用,如下所示:
import carsouler from "../components/library/carsouler.vue";
之后注册该组件,完整代码如下:
import carsouler from "../components/library/carsouler.vue";
export default {
name: "Computer",
components: {
carsouler: carsouler,
},
};
之后在<template><carsouler></carsouler></template>标签内直接这样使用就可以了。
- 我的微信
- 微信扫一扫加好友
-
- 我的微信公众号
- 扫描关注公众号
-





