本人前端開發(fā)一枚,以前一直用vue2.0,為了更新自己掌握的技術(shù)學(xué)習(xí)如何使用vue3.0。
在vue3.0項(xiàng)目中想要實(shí)現(xiàn)菜單組件,要使用到遞歸組件的方法,發(fā)現(xiàn)不知道怎么給組件重命名?。?/p>
在vue2.0中想要實(shí)現(xiàn)遞歸組件方式很簡(jiǎn)單,只要給組件命名,然后自己調(diào)用即可:
<template>
<div>
<menu-item :menuList="menuList"></menu-item> //調(diào)用自己
</div>
</template>
<script>
export default {
name: 'menuItem', //給組件命名
props: {
menuList: {
type: Array,
default: () => []
}
},
data () {
return {
}
}
}
</script>
<style scoped lang='less'>
</style>
然而在vue3.0中由于采用了script setup 語法糖,這種命名方式就不可行了,原因是它會(huì)自動(dòng)以文件名為主,不需要再寫name屬性:
<script setup>
</script>
后來發(fā)現(xiàn)直接在script setup同級(jí)中再添加一個(gè)script即可:
<template>
<div>
<menu-item :menuList="menuList"></menu-item> //調(diào)用自己
</div>
</template>
<script>
export default {
name: 'menuItem' //給組件命名
}
</script>
<script setup>
const props = defineProps({
menuList: {
type: Array,
default: () => []
}
})
</script>
<style scoped lang='less'>
</style>
使用插件:unplugin-vue-define-options 給組件定義別名
1.安裝插件
npm install unplugin-vue-define-options -D
2.在vite.config.js文件中配置
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import DefineOptions from 'unplugin-vue-define-options/vite'
export default defineConfig({
plugins: [vue(), DefineOptions()],
});
3.配置完成,在組件中使用:
<template>
<div>
<menu-item :menuList="menuList"></menu-item> //調(diào)用自己
</div>
</template>
<script setup>
defineOptions({
name: 'menuItem' //給組件命名
});
const props = defineProps({
menuList: {
type: Array,
default: () => []
}
})
</script>
<style scoped lang='less'>
</style>
使用了typescript的,可以配合插件直接在script標(biāo)簽中設(shè)置name,具體方式如下:
1.安裝插件:
npm install vite-plugin-vue-setup-extend文章來源:http://www.zghlxwxcb.cn/news/detail-457877.html
2.在script 標(biāo)簽中直接設(shè)置name即可:文章來源地址http://www.zghlxwxcb.cn/news/detail-457877.html
<script lang="ts" setup name="menuItem">
</script>
到了這里,關(guān)于vue3 組件自己引用自己 遞歸組件 組件命名的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!