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='http://www.aoyou183.cn/bcjs/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>
通過這種方式,就能實現組件的全局引用。
這種做的好處是對于復用性非常高的組件,省去了每次導入的麻煩;
缺點是無法直觀的看到組件引入和注冊,對于不清楚的人來說看不懂組件名的意義。
其實官方文檔中已經提到了一種解決方案:
https://cn.vuejs.org/v2/guide/components-registration.html#基礎組件的自動化全局注冊
基礎組件的自動化全局注冊
可能你的許多組件只是包裹了一個輸入框或按鈕之類的元素,是相對通用的。我們有時候會把它們稱為基礎組件,它們會在各個組件中被頻繁的用到。
所以會導致很多組件里都會有一個包含基礎組件的長列表:
import BaseButton from ‘./BaseButton.vue’ import BaseIcon from‘./BaseIcon.vue’ import BaseInput from ‘./BaseInput.vue’export default { components: {BaseButton,BaseIcon,BaseInput } }
而只是用于模板中的一小部分:
<BaseInput v-model=“searchText” @keydown.enter=“search” />
<BaseButton @click=“search”>
幸好如果你使用了 webpack (或在內部使用了 webpack 的 Vue CLI 3+),那么就可以使用 require.context 只全局注冊這些非常通用的基礎組件。這里有一份可以讓你在應用入口文件 (比如 src/main.js) 中全局導入基礎組件的示例代碼:
import Vue from ‘vue’ import upperFirst from ‘lodash/upperFirst’import camelCase from ‘lodash/camelCase’const requireComponent = require.context( // 其組件目錄的相對路徑‘./components’, // 是否查詢其子目錄 false, // 匹配基礎組件文件名的正則表達式/Base[A-Z]w+.(vue|js)$/ )requireComponent.keys().forEach(fileName => { // 獲取組件配置 constcomponentConfig = requireComponent(fileName)// 獲取組件的 PascalCase 命名 const componentName = upperFirst(camelCase(// 剝去文件名開頭的 ./ 和結尾的擴展名fileName.replace(/^./(.*).w+$/, ‘$1’)) )// 全局注冊組件 Vue.component(componentName,// 如果這個組件選項是通過 export default 導出的,// 那么就會優先使用 .default,// 否則回退到使用模塊的根。componentConfig.default || componentConfig ) })
補充知識:vue組件注冊 Vue.extend Vue.component Vue.use的使用 以及組件嵌套
我就廢話不多說了,大家還是直接看代碼吧~
/** * vue.extend用法 * 使用基礎 Vue 構造器,創建一個“子類”。參數是一個包含組件選項的對象。 * 注意:此實例可以掛載到根實例之外 */ const Profile = Vue.extend({ template: ’<p>{{firstName}} {{lastName}} aka {{alias}}</p>’, data: function () { return { firstName: ’Walter’, lastName: ’White’, alias: ’Heisenberg’ } } }) // 創建 Profile 實例,并掛載到一個元素上。 new Profile().$mount(’#opp’)let navbar = { template: `<div class=’nav’> <input type='text' placeholder='請輸入關鍵字'/> </div>`, data:()=>{ return { } }, mounted() { console.log(this.$parent) }};const MyPlugin = { install:(vue, arguments)=>{ console.log(arguments); vue.component(’navbar’, navbar); }}Vue.use(MyPlugin, {a:1, b:2}); // 組件注冊成功// logo組件Vue.component('logo', { template: `<div class=’logo’> <img v-bind:src='http://www.aoyou183.cn/bcjs/logoSrc'> </div>`, inject: [’logoSrc’], data:()=>{ return { } }, mounted() { console.log(this.$parent) }})// header組件 組件調用 provie inject傳值Vue.component('buttoncounter', { template: `<div class=’header’> <logo></logo> {{header}} </div>`, provide:{ logoSrc:’https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582433251882&di=de459decf2e157552b97a4879ae4135d&imgtype=0&src=http%3A%2F%2Fwww.suntop168.com%2Fblog%2Fzb_users%2Fupload%2F2014%2F2%2Fadf89182.jpg’ }, data:()=>{ return { header:’我是頭部導航欄’ } }, mounted() { console.log(this.$parent) }});// vue根實例let vm = new Vue({ el:'#app', data:{ name: ’Marry’ }, mounted(){ console.log(’vue根實例初始化完畢’) }})console.log(vm);
以上這篇Vue 實現創建全局組件,并且使用Vue.use() 載入方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。