本人前端开发一枚,以前一直用vue2.0,为了更新自己掌握的技术学习如何使用vue3.0。
在vue3.0项目中想要实现菜单组件,要使用到递归组件的方法,发现不知道怎么给组件重命名!!
在vue2.0中想要实现递归组件方式很简单,只要给组件命名,然后自己调用即可:
<template> <div> <menu-item :menuList="menuList"></menu-item> //调用自己 </div> </template> <script> export default { name: 'menuItem', //给组件命名 props: { menuList: { type: Array, default: () => [] } }, data () { return { } } } </script> <style scoped lang='less'> </style>
复制
然而在vue3.0中由于采用了script setup 语法糖,这种命名方式就不可行了,原因是它会自动以文件名为主,不需要再写name属性:
<script setup> </script>
复制
后来发现直接在script setup同级中再添加一个script即可:
<template> <div> <menu-item :menuList="menuList"></menu-item> //调用自己 </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> //调用自己 </div> </template> <script setup> defineOptions({ name: 'menuItem' //给组件命名 }); const props = defineProps({ menuList: { type: Array, default: () => [] } }) </script> <style scoped lang='less'> </style>
复制
使用了typescript的,可以配合插件直接在script标签中设置name,具体方式如下:
1.安装插件:
npm install vite-plugin-vue-setup-extend
2.在script 标签中直接设置name即可:
<script lang="ts" setup name="menuItem"> </script>
复制