自定義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>
通過這種方式,就能實現組件的全局引用。
這種做的好處是對於複用性非常高的組件,省去了每次導入的麻煩;
缺點是無法直觀的看到組件引入和註冊,對於不清楚的人來說看不懂組件名的意義。