Vue 实现创建全局组件实现创建全局组件,并且使用并且使用Vue.use() 载入方式载入方式
自定义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组件。组件。
评论0