功能: 想實現自動化全局注冊組件
const componentsContext = require.context('./components', true, /Base[A-Z]\w+\.(vue|js)$/); console.log('????',componentsContext,componentsContext.keys()); componentsContext.keys().forEach(component => { // 獲取文件中的 default 模塊 const componentConfig = componentsContext(component).default; console.log(componentsContext(component).default); Vue.component(componentConfig.name, componentConfig) })
報錯:
結果:未解決
原因:為了編譯至各平台,編譯器是靜態分析代碼,掃描組件來編譯,所以不支持動態注冊,短期內應該不會支持動態組件注冊
全局組件
uni-app
支持配置全局組件,需在 main.js
里進行全局注冊,注冊后就可在所有頁面里使用該組件。
注意
Vue.component
的第一個參數必須是靜態的字符串。- nvue頁面暫不支持全局組件
示例
main.js 里進行全局導入和注冊
import Vue from 'vue' import pageHead from './components/page-head.vue' Vue.component('page-head',pageHead)
index.vue 里可直接使用組件
<template> <view> <page-head></page-head> </view> </template>
相關資料: