vue引入組件的幾種方法匯總
更新時間:2023年10月10日 10:55:00 作者:鄭建007
這篇文章主要介紹了vue引入組件的幾種方法匯總,包括常用的局部引入,這里需要注意在哪個頁面需要就在那個頁面引入、注冊、使用,本文結合示例代碼給大家介紹的非常詳細,需要的朋友參考下吧
一、常用的局部引入
<template>
<div>
<!--3.使用組件-->
<Button></Button>
</div>
</template>
<script>
// 1. 引入組件
import Button from '../view/button.vue'
export default {
// 2. 注冊組件
components: {
Button,
}
}
</script>總結: 在哪個頁面需要就在那個頁面引入、注冊、使用
二、創(chuàng)建一個js 進行統(tǒng)一注冊 然后在main.js引入統(tǒng)一管理的js文件實現(xiàn)全局注冊
1、global.js統(tǒng)一注冊管理:
// 1.引入vue import Vue from 'vue' import Child1 from './child1' import Child2 from './child1' import Child3 from './child1' import Child4 from './child1' import Child5 from './child1' Vue.component(Child1) Vue.component(Child2) Vue.component(Child3) Vue.component(Child4) Vue.component(Child5)
2、在main.js中引入 global.js實現(xiàn)全局注冊
優(yōu)點: 減少每個頁面引入的繁瑣步驟 、減少了每一頁面重復引入的代碼,
缺點: 有90%的代碼都是重復的
三、自動注冊全局引入
注釋版:
// 引入vue
import Vue from 'vue'
// 將字符串首字母大寫 返回當前字符串
function changeStr(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
// require.context: 是動態(tài)引入文件
// 參數(shù)一: 當前路徑(引入.vue文件的當前路徑)
// 參數(shù)二:是否匹配當前文件下的子文件
// 參數(shù)三:查找文件格式以.vue結尾的文件
const requireComponent = require.context('./', false, /\.vue$/)
console.log("批量注冊組件", requireComponent.keys()) // ['./head-l.vue', './head-r.vue', './head.vue']
requireComponent.keys().forEach(fileName => {
// 當前組件
const config = requireComponent(fileName)
console.log("組件的信息config", config)
//獲取組件名
const componentName = changeStr(fileName.replace(/^\.\//, '').replace(/\.\w+$/)) // 第一個replace(/^\.\//, '')去掉前面的./ 第二個replace(/\.W+$/)是去掉后面的.vue
console.log("組件名", componentName) // 例如:Head-rundefined
// 參數(shù)一: 組件名
// 參數(shù)二: config:是一整個組件的內容; config.default:是組件中export.default里面的內容
Vue.component(componentName, config.default || config)
})純凈版:
import Vue from 'vue'
function changeStr(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
const requireComponent = require.context('./', false, /\.vue$/)
requireComponent.keys().forEach(fileName => {
const config = requireComponent(fileName)
const componentName = changeStr(fileName.replace(/^\.\//, '').replace(/\.\w+$/))
Vue.component(componentName, config.default || config)
})結構:

到此這篇關于vue引入組件的幾種方法的文章就介紹到這了,更多相關vue引入組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue中引入bootstrap.min.css的正確姿勢分享
這篇文章主要介紹了Vue中引入bootstrap.min.css的正確姿勢,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

