欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue引入組件的幾種方法代碼示例

 更新時間:2024年04月01日 10:32:57   作者:鄭建零零發(fā)  
vue的一個強大功能就是組件化開發(fā),下面這篇文章主要給大家介紹了關于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)引入文件
// 參數一: 當前路徑(引入.vue文件的當前路徑)
// 參數二:是否匹配當前文件下的子文件
// 參數三:查找文件格式以.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
	// 參數一: 組件名
	// 參數二: 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 中 import引入相同的方法名稱解決方法

import { list } from '@/api/aaaa/apiJs'
import { list} from '@/api/bbb/apiJs'

當引入了2個不同的文件,方法名稱list都是一樣的,就會出現(xiàn)報錯。

如果之前文件用的地方比較多,直接改名稱的話,可能會漏掉,會引起不必要的麻煩,那如何解決呢

解決方法:

import { list } from '@/api/aaaa/apiJs'
import { list as _list} from '@/api/bbb/apiJs'

就是使用 import as

as后面的名字就是你要替換的名稱,是不是很簡單就解決了

總結 

到此這篇關于vue引入組件的幾種方法的文章就介紹到這了,更多相關vue引入組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論