Vue itself and its surrounding ecology have hardly disappointed me in designing syntax sugar, including Vue Vine, which was officially unveiled at the VueConf 2024 Shenzhen event.
Its appearance has aroused my curiosity about how Vue3 components are written, and which approaches "best practices"?
So what interesting tool is Vue Vine? And what other tools are similar to this tool? What are their corresponding scenarios? How to choose?
Let me tell you one by one:
SFC single file component
When we write code, we often have duplicate code, such as:
<template> <dialog v-if="showInDialog"> <!-- Code snippet --> </dialog> <div v-else> <!-- Code snippet --> </div> </template>
If we don't want to "Code snippet"What should I do if I write this part repeatedly twice?
At this time, we often take out this code snippet and put it in a newly created one..vue
In subcomponents:
<!-- Parent component --> <template> <dialog v-if="showInDialog"> <Content /> </dialog> <div v-else> <Content /> </div> </template> <!-- Subcomponents --> <template> <!-- Code snippet --> </template>
This itself is a componentized development method that Vue officially defaults to, that is, SFC single-file components.
However, in some cases, we may not want to split this part of the "code snippet" into separate single files. For example, when the "code snippet" is very simple, or when the parent component does not have much code...
And the series of tedious operations brought about by forced splitting are sometimes quite annoying. At this time, we have to find some solutions to solve this situation where a single file component cannot solve it.
Multi-template solution
The multi-template solution emphasizes theA single file componentExtracting energyReused templatesCode, in other words, extract the public HTML generation.
createReusableTemplate
VueUseIt is a tool library that provides a lot of practical Vue3 composables, which provides a reusable template.createReusableTemplate
Method, the document link is/core/createReusableTemplate
How to use is very simple:
<script setup> import { createReusableTemplate } from '@vueuse/core' const [DefineTemplate, ReuseTemplate] = createReusableTemplate() </script> <template> <DefineTemplate> <!-- Code snippet --> </DefineTemplate> <dialog v-if="showInDialog"> <ReuseTemplate /> </dialog> <div v-else> <ReuseTemplate /> </div> </template>
Use importedDefineTemplate
Component registration template (note that the content will not be rendered at this time), and then use itReuseTemplate
Components to render the template you just registered (note that DefineTemplate must be used before ReuseTemplate).
namedTemplate
Vue MacrosLike magic, it allows you to experience more advanced syntactic sugar in Vue3 projects. And it is also a test field for Vue grammar, and many grammars in it have the chance to be included by Vue!
It provides a named templatenamedTemplate
Features, the document link is/zh-CN/features/
How to use it is as follows:
<script setup> const showInDialog = ref(false) </script> <template name="reusable"> <!-- Code snippet --> </template> <template> <template v-if="showInDialog"> <dialog> <template is="reusable" /> </dialog> </template> <template v-else> <div> <template is="reusable" /> </div> </template> </template>
Multi-component (stateless) scheme
The multi-component (stateless) scheme emphasizes theA fileDefinition inSingle stateful component + Multiple stateless components
JSX
JSX is the most common solution in multi-component practice, dominating the "multi-component (stateless) solution". There are many ways to write in JSX solutions, involving the knowledge of stateful "components" and stateless "function components".
I'll choose three common solutions here:defineComponent render
、defineRender
、setupSFC
, other writing styles are not mainstream, so we won’t mention them here.
defineComponent render
This is the most unpretentious way to use JSX in Vue3! Belongs to Vue3 + JSXWhere the dream begins
import { defineComponent, ref } from "vue" export default defineComponent({ setup() { // Use ref to create a responsive variable to control the display status const showInDialog = ref(false) // Declare a stateless function component Content for rendering code snippets function Content() { return <div>Code snippet</div> } // Return the render function return () => ( <div> { ? ( <dialog> <Content /> </dialog> ) : ( <div> <Content /> </div> )} </div> ) } })
defineComponent
Methods are used to define components, insetup
Inside the method, we can use "function components" to define some "stateless components" that need to be reused, and finally return the render function directly.
Essentially, it isdefineComponent + render + stateless function component + JSX"Combined use
defineRender
And defineRender can be regarded asdefineComponent render
It's also an upgraded versionVue MacrosMethod provided.
usedefineRender
Can be directly in<script setup>
Define the rendering function in:
<script setup lang="jsx"> // Use ref to create a responsive variable to control the display statusconst showInDialog = ref(false) // Declare a stateless function component Content for rendering code snippetsfunction Content() { return <div>Code snippet</div> } defineRender( <div> { ? ( <dialog> <Content /> </dialog> ) : ( <div> <Content /> </div> )} </div> ) </script>
Although this method has been said goodbyedefineComponent
andOptions API
Make the code lighter, but.vue
Written in the middlejsx
Still not elegant enough.
So there is an upgraded version about itsetupSFC
!
setupSFC
setupSFC is one of my favorite solutions for writing JSX components in Vue3 (it is stillVue Macrosprovided method).
When we develop, we need to define the suffix as. / .
File:
// Use ref to create a responsive variable to control the display statusconst showInDialog = ref(false) // Declare a stateless function component Content for rendering code snippetsfunction Content() { return <div>Code snippet</div> } export default () => ( <div> { ? ( <dialog> <Content /> </dialog> ) : ( <div> <Content /> </div> )} </div> )
Say goodbyedefineComponent
andOptions API
,Willsetup
andjsx
Perfect fusion.
Multi-component (stateful) scheme
The multi-component (stateful) scheme emphasizes theA fileDefinition inMultiple stateful components
JSX
That’s right, after JSX dominated the “multi-component (stateless) scheme”, it is also active in the “multi-component (stateless) scheme”!
defineComponent render
In fact, we have defined the "defineComponent render" mentioned above several times, which is the plan.
import { defineComponent, ref } from "vue" // Subcomponentsconst Content = defineComponent({ setup() { return () => <div>Code snippet</div> } }) // Parent componentconst App = defineComponent({ setup() { const showInDialog = ref(false) return () => ( <div> { ? ( <dialog> <Content /> </dialog> ) : ( <div> <Content /> </div> )} </div> ) } }) export default App
Stacking in a filedefineComponent
That's right, this form is similar to that in React"Class Component"
setupComponent
now that"Class Component"Yes, then is there"State Function Components"Woolen cloth?
thenVue MacrosIt also provides a very cool syntax setupComponent that can be used in.jsx
There are multiple "stateful function components" written in the file, which is my favorite solution to write JSX components in Vue3.
// Subcomponentsconst Content = defineSetupComponent(() => { return <div>Code snippet</div> }) // Parent componentconst App = defineSetupComponent(() => { const showInDialog = ref(false) return ( <div> { ? ( <dialog> <Content /> </dialog> ) : ( <div> <Content /> </div> )} </div> ) }) export default App
Vue Vine
Have you found that all the multi-component solutions in the article so far are based on JSX. Is there any oneUse templates and support multiple componentsWhat about the plan?
Then we have to talk about Vue Vine.
It is worth noting that Vine only supports itVue3 + Vite + TS
, then we build a.
document:
// Subcomponentsfunction Content() { return vine`<div>Code snippet</div>` } // Parent componentfunction App() { const showInDialog = ref(false) return vine` <div> <template v-if="showInDialog"> <dialog> <Content /> </dialog> </template> <template v-else> <div> <Content /> </div> </template> </div> ` } export default App
A function is a component, and thenvine
Tagged template string declares component templates.
This writing method is just mentionedsetupComponent
Very similar, all belong"State Function Components", but the difference is that one returns JSX and the other returns template. The advantage of templates is that Vue has compile-time optimizations for it.
Summarize
- In most cases, the first choice is still
SFC single file component
Just plan - For template reuse, I prefer the one provided by Vue Macros
namedTemplate
However, given the current stability, it is recommended to use the provided by VueUsecreateReusableTemplate
plan - For multi-component scenarios, it is recommended that you choose JSX solutions as the first choice.
defineComponent render
plan. Developers who like to try it out can boldly try it out by Vue MacrossetupComponent
Or chooseVue Vine
End
The above is the detailed content of N multiple-component writing methods of Vue3. For more information about the multi-component writing methods of Vue3, please pay attention to my other related articles!