introduction
If you use it in vue3 development<script setup>
In terms of syntax, additional processing is needed for the component's name attribute.
For [email protected] and above, use<script setup>
When a single-file component is used, vue will automatically deduce the name attribute based on the component file name. That is, a file named or , the name attribute is MyComponent, and when you display the defined name attribute in the component, the derived name will be overwritten.
The name attribute of the component can not only be used for<KeepAlive>
, and in usevuejs-devtools
When the plug-in debugs the code, the corresponding components can also display their name attributes, which facilitates us to quickly locate the code and debug. The definition name attribute displayed is a good habit.
Besides that, if we are going to<script setup>
To display the definition name attribute, you need to add an additional script, that is:
<script> export default { name: "MyComponent" } </script> <script setup lang="ts"> ... <script>
It's a bit complicated, and the community has launchedunplugin-vue-define-options
to simplify this operation.
Steps to use
- Install
npm i unplugin-vue-define-options -D
- Configure vite
// import DefineOptions from 'unplugin-vue-define-options/vite' import Vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [Vue(), DefineOptions()], })
- If you develop with typescript, you need to configure typescript support
// { "compilerOptions": { // ... "types": ["unplugin-vue-define-options/macros-global" /* ... */] } }
After the installation configuration is completed, you can use the provideddefineOptions
API to define the name attribute.
<script setup lang="ts"> defineOptions({ name: "MyComponent" }) <script>
So how does it do this?
For usedefineOptions
Code:
<script setup lang="ts"> import { useSlots } from 'vue' defineOptions({ name: 'Foo', inheritAttrs: false, }) const slots = useSlots() </script>
After compilation, the output is:
<script lang="ts"> export default { name: 'Foo', inheritAttrs: false, props: { msg: { type: String, default: 'bar' }, }, emits: ['change', 'update'], } </script> <script setup> const slots = useSlots() </script>
It can be found that this is the same as when we wrote 2 script tags above, that is,unplugin-vue-define-options
Through the vite plug-in, we helped us write 2 scripts during the compilation stage, simplifying our development.
The above is a detailed explanation of the techniques for using vue3 name attribute. For more information on the use of vue3 name attribute, please follow my other related articles!