本人前端开发一枚,以前一直用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 unpluginvuedefineoptions -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 vitepluginvuesetupextend

2.在script 标签中直接设置name即可

<script lang="ts" setup name="menuItem">

</script>

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注