Vue3 components refer to themselves recursively component component naming

I developed a front-end one. I have been using vue2.0 before. In order to update my own technology, I learned how to use vue3.0.

In the vue3.0 project, if you want to implement the menu component, you need to use the recursive component method, but you don't know how to rename the component! !

It is very simple to implement recursive components in vue2.0, just name the component and call it yourself:

<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>

However, due to the use of script setup syntax sugar in vue3.0, this naming method is not feasible, because it will automatically use the file name as the main name, and there is no need to write the name attribute:

<script setup>
</script>

Later, it was found that adding another script directly to the same level of script setup:

<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. Install the plugin

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. The configuration is complete and used in the component:

<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>

If you use typescript , you can directly set the name in the script tag with the plug-in. The specific method is as follows:

1. Install the plugin:

npm install vite-plugin-vue-setup-extend

2. Just set the name directly in the script tag:

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

</script>

Guess you like

Origin blog.csdn.net/weixin_39823006/article/details/129396670