Vue3.2 setup syntax sugar
Vue3.2 setup syntax sugar [Synonym sugar for single file components<script setup>
]
If you have a certain understanding of Vue3 syntax sugar, it is better to eat it with another article from me!Vue3 must-learn skills-customized Hooks-making writing of Vue3 more convenient
Reading originally, by default, you already have a certain understanding of the composition API of Vue3.0, but it is troubled by the need for cumbersome return-related variables and functions in the setup function, so the syntax sugar of setup<script setup>
You will gain a lot. Syntactic sugar<script setup>
The introduction makes it more exciting to write Vue3 and makes Vue3 fuller. This article is written based on official documents. If you have time, it is recommended toOfficial DocumentationRead above, this article is written more semantic and popular, I hope you like it.
<script setup>
is a compile-time syntax sugar using a combination API in a single file component (SFC)
Solving that setup in Vue3.0 requires tedious exposure of declared variables, functions and import content to be introduced through return to the setup in order to expose it in<template/>
Issues of use
1. Use <script setup> in <template/>
<script setup>
In the variables, functions and contents introduced by import without return declaration, you can<template/>
use
<script setup>
Syntactic sugar
<script setup> // Content introduced by importimport { getToday } from './utils' // Variableconst msg = 'Hello!' // Functionfunction log() { (msg) } </script> //Template declared variables, functions and content introduced by import<template> <div @click="log">{{ msg }}</div> <p>{{getToday()}}</p> </template>
Standard Components<script>
Need to write a setup function and return it cumbersomely
<script> // Content introduced by importimport { getToday } from './utils' export default{ setup(){ // Variable const msg = 'Hello!' // Function function log() { (msg) } //If you want to use it in tempate, you need to expose it in setup. return{ msg, log, getToday } } } </script> <template> <div @click="log">{{ msg }}</div> <p>{{getToday()}}</p> </template>
summary:<script setup>
The code in syntax sugar will be compiled into componentssetup()
The content of the function does not need to be exposed through return to the declared variables, functions and content introduced by import, so that<template/>
Used and does not need to writeexport default{}
<script setup>
The code in syntax sugar will be compiled into componentssetup()
The content of the function. This means with ordinary<script>
Only execute once a different component when it is first introduced.<script setup>
The code inExecute each time a component instance is created
<script> ('script');//Instance component multiple times, only triggered once export default { setup() { ('setupFn');//Every time the component is instantiated, the same as the script-setup tag is triggered } } </script>
(script-setup tags will eventually be compiled intosetup()
The content of the function, each time the component is instantiated, the setup function is instantiated once. The setup function in the script tag is the same. Every time the component is instantiated, the setup function is instantiated once, but the script tag setup needs to be written inside the export default{}, and the outside is only executed once when it is first introduced)
2. The <script setup> component will be automatically registered
It does not need to be introduced after the component is introduced,components:{}
Register components, can be used directly
&lt;script setup&gt; import MyComponent from './' //components:{MyComponent} does not require registration and use it directly&lt;/script&gt; &lt;template&gt; &nbsp;&lt;MyComponent /&gt; &lt;/template&gt;
3. Component communication:
exist<script setup>
Must be used indefineProps
and defineEmits
API to replace props and emits
defineProps
anddefineEmits
Have complete type inference and<script setup>
Medium YesDirectly available(I browsed the Nuggets and found that most of the article demos still introduce these two APIs through import, and the official documentation is very clear)
defineProps instead of props
Receive data passed by the parent component (the parent component passes parameters to the child component)
Parent component:
<template> <div>Parent component</div> <Child :title="msg" /> </template> <script setup> import {ref} from 'vue' import Child from './' const msg = ref('The value of the parent') //Return automatically, use directly in template</script>
Subcomponents:
<template/>
Props that can be passed directly using the parent component (props can be omitted)
<script-setup>
Need to get the props passed by the parent component
<template> <div>Subcomponents</div> <div>Values passed by the parent component:{{title}}</div> </template> <script setup> //import {defineProps} from 'vue' does not require import// Syntax sugar must use defineProps instead of propsconst props = defineProps({ title: { type: String } }); //script-setup requires the props passed by the parent component() //The value of the parent</script>
defineEmit instead of emit
The child component passes data to the parent component (the child component exposes data to the outside)
Subcomponent code:
<template> <div>Subcomponents</div> <button @click="toEmits">Subcomponents向外暴露数据</button> </template> <script setup> import {ref} from 'vue' const name = ref('I am a child component') //1. Expose internal dataconst emits = defineEmits(['childFn']); const toEmits = () => { //2. Trigger the exposed childFn method in the parent component and carry data emits('childFn',name) } </script>
Parent component code:
<template> <div>Parent component</div> <Child @childFn='childFn' /> <p>Receive data passed by subcomponents{{childData}} </p> </template> <script setup> import {ref} from 'vue' import Child from './' const childData = ref(null) const childFn=(e)=>{ ('The child component triggers the parent component childFn and passes the parameter e') childData= } </script>
4. <script setup> needs to actively expose child component properties to the parent component: defineExpose
use<script setup>
The parent component cannot pass ref or$parent
Obtain the response data such as ref of the child component, and it needs to be actively exposed through defineExpose.
Subcomponent code:
<script setup> import { ref } from 'vue' const a = 1 const b = ref(2) //Actively expose component propertiesdefineExpose({ a, b }) </script>
Parent component code:
<template> <div>Parent component</div> <Child ref='childRef' /> <button @click='getChildData'>passrefGet the properties of the child component </button> </template> <script setup> import {ref} from 'vue' import Child from './' const childRef= ref() //Register response dataconst getChildData =()=>{ //The value of the subcomponent receiving and exposure is exposed () //1 () //2 Responsive data} </script>
5. Other functions of syntax sugar
useSlots
anduseAttrs
(Use lessSince most people are developing SFC model,<template/>
pass<slot/>
Tags can render slots)
If neededscript-setup
Used inslots
andattrs
Need to useuseSlots
anduseAttrs
Alternative
Need to introduce: import { useSlots ,useAttrs } form 'vue'
exist<template/>
Passed$slots
and$attrs
It is more convenient to access (attrs is used to obtain parameters/methods passed in the parent component to the child component, attrs is used to obtain parameters/methods passed in the parent component to the child component, attrs is used to obtain parameters/methods passed in the parent component to the child component, slots can obtain virtual dom objects passed in the slots in the parent component, which should not be very useful in SFC mode, and is used more frequently in JSX/TSX)
Parent component:
<template> <Child msg="Non-porps value transmission subcomponent receives with attrs" > <!-- Anonymous slots --> <span >Default slot</span> <!-- Named slots --> <template #title> <h1>Named slots</h1> </template> <!-- Scope slots --> <template #footer="{ scope }"> <footer>Scope slots——Name:{{ }},age{{ }}</footer> </template> </Child> </template> <script setup> // Introduce subcomponentsimport Child from './' </script>
Subcomponents:
<template> <!-- Anonymous slots --> <slot /> <!-- Named slots --> <slot name="title" /> <!-- Scope slots --> <slot name="footer" :scope="state" /> <!-- $attrs Used to obtain non-in-parent componentpropsParameters passed to subcomponents --> <p>{{ == $ }}</p> <!--true Didn't expect it to work... --> <p>{{ slots == $slots }}</p> </template> <script setup> import { useSlots, useAttrs, reactive, toRef } from 'vue' const state = reactive({ name: 'Zhang San', age: '18' }) const slots = useSlots() (()); //Get the virtual dom object to the default slot(()); //Get the virtual dom object with the named title slot// (()); // Report an error. I don’t know why the slot scope cannot be obtained.//useAttrs() is used to obtain the incoming attribute data (that is, the attribute value of non-props) passed by the parent component.const attrs = useAttrs() </script>
useSlots may be more practical under JSX/TSX
If you want to use JSX syntax, you need to download the relevant jsx plugins in vite to recognize jsx
useSlots can obtain the virtual dom object passed by the slot from the parent component, which can be used to render the slot content.
<script lang='jsx'> import { defineComponent, useSlots } from "vue"; export default defineComponent({ setup() { // Get slot data const slots = useSlots(); // Rendering component return () => ( <div> {?():''} {?():''} </div> ); }, }); </script>
Most people develop SFC model,<template/>
pass<slot/>
The slot can be rendered by tags. This JSX writing method should be used by few people.
6. Access the route in setup
- Access routing instance component information: route and router
setup
Not accessible inthis
, no longer directly accessedthis.$router
orthis.$route
. (getCurrentInstance can replace this but is not recommended)
Recommended: UseuseRoute
Functions anduseRouter
Function substitutionthis.$route
andthis.$router
<script setup> import { useRouter, useRoute } from 'vue-router' const route = useRoute() const router = useRouter() function pushWithQuery(query) { ({ name: 'search', query: { ..., }, }) } <script/>
- Navigation Guard
Navigation guards for routing instance components are still available
import router from './router' ((to,from,next)=>{ })
You can also use the combined api navigation guard onBeforeRouteLeave, onBeforeRouteUpdate
<script setup> import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router' // Same as beforeRouteLeave, `this` cannot be accessed onBeforeRouteLeave((to, from) => { const answer = ( 'Do you really want to leave? you have unsaved changes!' ) // Cancel navigation and stay on the same page if (!answer) return false }) const userData = ref() // Same as beforeRouteUpdate, `this` cannot be accessed onBeforeRouteUpdate(async (to, from) => { //Get the user only if the id changes, for example only query or hash value has been changed if ( !== ) { = await fetchUser() } }) <script/>
Combined API guards can also be used in any component rendered by `<router-view>`, and they do not have to be used directly on routing components like in-component guards.
Summary: The syntax sugar of setup is used as a supplement to Vue3, making Vue3 more full and making it more enjoyable to write Vue3. If you think the writing is pretty good, please give me some praise before leaving!
If you feel that you are still unsatisfied after reading it, what is the best thing about not getting Vue3? Please learn about Vue3’s custom hooks!
Vue3 and custom Hooks may be the complete body of Vue3! Because some people still think that writing Vue3 functions and variables together is not elegant after reading this article! You might as well read this article!
Vue3 programming smooth tips customize Hooks
The above is the detailed content of Vue3 programming smooth skills that use setup syntax sugar to refuse to write return. For more information about Vue3 programming syntax sugar, please pay attention to my other related articles!