自定义vue组件,一般是局部引用的方式载入,使用的时候,在应用的组件中使用 import moduleName from ‘module’ 导入,在components中注册
<template>
<div class="app-NewsInfo">
<h3>{{info.title}}</h3>
<!-- 新闻评论子组件。 -->
<comment :id="id"></comment>
</div>
</template>
<script>
import comment from "../sub/comment.vue";
export default {
data() {
return {
info: {},
id: this.$route.query.id
};
},
methods: {},
components: {
comment
},
</script>
那么如果某个组件经常复用,岂不是每次在新组建中引用都要导入一次吗?是的 。这种情况下可以将组件封装成全局组件,一次导入之后,全局都可以使用。
1.首先创建一个文件夹loading
用来保存需要全局引用的组件,并且存放一些配置文件。
2.创建一个loading.vue的组件。
该组件中除了组件的基础结构,并无其他内容。它的作用是用来加载准备自定义的组件,最后将loading组件加载到全局的Vue中,这样就一次性完成了所有自定义组件的加载,非常方便。
<template>
<div class="loading"></div>
</template>
<script>
export default {
data() {
return {};
},
methods: {}
};
</script>
<style scoped>
</style>
3.创建自定义组件
这里以一个简单封装的mint-ui轮播图为例。
<template>
<div class="app-turns">
<mt-swipe :auto="4000">
<mt-swipe-item v-for="(item,i) of list" :key="i">
<img :src="item.img_url" @click="detail" :data-id="item.id">
</mt-swipe-item>
</mt-swipe>
</div>
</template>
<script>
export default {
name: "navbar",
props: ["list"], //接收父组件数据
data() {
return {
};
},
methods: {
detail(e) {
var id = e.target.dataset.id;
var url = `/GoodsInfo/${id}`;
this.$router.push(url);
}
},
created() {}
};
</script>
<style scoped>
.mint-swipe {
height: 150px;
}
.mint-swipe img {
width: 100%;
}
</style>
4.创建index.js,用来导出所有自定义组件。
import turns from './turns.vue'
const loading = {
install: function (Vue) {
Vue.component('turns', turns)
}
}
export default loading;
其实到这里组件封装就结束了,下面再演示下如何使用。
5.在main.js中,导入并使用loading组件。
import loading from './lib/loading';
Vue.use(loading);
这样就将组件全局引用成功了!
6.在需要使用的地方,直接使用组件名即可。
<template>
<div class="app-home">
<turns :list="list"></turns>
</div>
</template>
通过这种方式,就能实现组件的全局引用。
这种做的好处是对于复用性非常高的组件,省去了每次导入的麻烦;
缺点是无法直观的看到组件引入和注册,对于不清楚的人来说看不懂组件名的意义。
===============备注===================
该文可以清晰解释为什么引用模块loading 的时候,使用的是标签turns ,其实是一个包含关系,即组件库名和单个组件名。就好像你引入了elementUI组件库,具体使用哪个组件就是用该组件的标签。
作者:SilenceJude
来源:CSDN
原文:https://blog.csdn.net/SilenceJude/article/details/85088764
版权声明:本文为博主原创文章,转载请附上博文链接!