Vue3中name有什么用呢?

科技公元 前端 2022-11-30

1.在递归组件的时候需要定义name

2.配合keep-alive include exclude 可以缓存组件

3.在Vue有报错或者调试的时候可以看到组件的name

Vue3 定义 name

1.自动生成

<script setup> 只要在script开启setup语法糖模式 单文件组件会自动根据文件名生成对应的 name 选项 例如 Tree.vue 那他的name 就是 Tree 自动生成,这样做有一个弊端如果想修改name需要修改组件名称如果有地方import 该组件需要一并修改。

2.在开启一个script用来定义name

优点 这种方式可以随意定义name 弊端 一个单文件组件出现两个script 会让人感到疑惑。

<template> <div></div> </template> <script lang="ts" setup> import {ref,reactive } from 'vue' </script> <script lang='ts'>  export default {     name:"XXX"  } </script> <style lang="less" scoped> </style> 复制代码

3.使用第三方插件 unplugin-vue-define-options

安装方法   npm i unplugin-vue-define-options -D

vite 使用

// vite.config.ts import DefineOptions from 'unplugin-vue-define-options/vite' import Vue from '@vitejs/plugin-vue' export default defineConfig({   plugins: [Vue(), DefineOptions()], }) 复制代码

配置tsconfig.json

// tsconfig.json {   "compilerOptions": {     // ...     "types": ["unplugin-vue-define-options/macros-global" /* ... */]   } } 复制代码

使用方法 通过编译宏 defineOptions 添加nameinheritAttrs

<script setup lang="ts"> defineOptions({   name: 'Foo',   inheritAttrs: false, }) </script> 复制代码

4.个人想法 我想着直接在script 定义name 不好吗?

<template> <div></div> </template> <script name="xiaoman" lang="ts" setup> import {ref,reactive } from 'vue' </script> <style lang="less" scoped> </style>
Apipost 私有化火热进行中

评论