SoFunction
Updated on 2025-04-04

Share the tutorial on using setup syntax sugar in Vue3.2

Tip: Only when vue 3.2 version can you use syntax sugar!

In Vue3.0, variables must be returned and can only be used in template; in Vue3.2, you only need to add the setup attribute to the script tag, and you can use it directly without  return, template  , which is very delicious!

Tip: The following is the main content of this article, and the following cases are for reference

1. How to use setup syntax sugar

Just write the setup code on the script tag as follows (example):

<template>
</template>
<script setup>
</script>
<style scoped lang="less">
</style>

2. Use of data data

Since setup does not require writing return, you can declare the data directly. The code is as follows (example):

&lt;script setup&gt;
    import {
      ref,
reactive,
      toRefs,
    } from 'vue'
    const data = reactive({
      patternVisible: false,
      debugVisible: false,
      aboutExeVisible: false,
    })
    const content = ref('content')
    //Use toRefs to deconstruct    const { patternVisible, debugVisible, aboutExeVisible } = toRefs(data)
&lt;/script&gt;

3. Use of method method

The code is as follows (example):

&lt;template &gt;
    &lt;button @click="onClickHelp"&gt;System Help&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import {reactive} from 'vue'
const data = reactive({
      aboutExeVisible: false,
})
// Click Helpconst onClickHelp = () =&gt; {
    (`System Help`)
     = true
}
&lt;/script&gt;

4. Use of watchEffect

The code is as follows (example):

&lt;script setup&gt;
import {
  ref,
  watchEffect,
} from 'vue'
let sum = ref(0)
watchEffect(()=&gt;{
  const x1 = 
  ('The callback specified by watchEffect has been executed')
})
&lt;/script&gt;

5. Use of watch

The code is as follows (example):

&lt;script setup&gt;
    import {
      reactive,
      watch,
    } from 'vue'
     //data     let sum = ref(0)
     let msg = ref('hello')
     let person = reactive({
                    name:'Zhang San',
                    age:18,
                    job:{
                      j1:{
                        salary:20
                      }
                    }
                  })
    // Two listening formats    watch([sum,msg],(newValue,oldValue)=&gt;{
            ('sum or msg changed',newValue,oldValue)
          },{immediate:true})
     watch(()=&gt;,(newValue,oldValue)=&gt;{
        ('person's job has changed',newValue,oldValue)
     },{deep:true}) 
&lt;/script&gt;

6. Use of computed computing attributes

There are two ways to write computed computing properties (abbreviation and complete writing that considers reading and writing). The code is as follows (example):

&lt;script setup&gt;
    import {
      reactive,
      computed,
    } from 'vue'
    //data    let person = reactive({
       firstName:'Small',
       lastName:'Dingdang'
     })
    // Abbreviation of Computational Properties     = computed(()=&gt;{
        return  + '-' + 
      }) 
    // Complete writing     = computed({
      get(){
        return  + '-' + 
      },
      set(value){
        const nameArr = ('-')
         = nameArr[0]
         = nameArr[1]
      }
    })
&lt;/script&gt;

7. Use of props parent-child value transmission

The subcomponent code is as follows (example):

&lt;template&gt;
  &lt;span&gt;{{}}&lt;/span&gt;
&lt;/template&gt;
&lt;script setup&gt;
  import { defineProps } from 'vue'
  // Declare props  const props = defineProps({
    name: {
      type: String,
      default: '11'
    }
  })  
  // or  //const props = defineProps(['name'])
&lt;/script&gt;

The parent component code is as follows (example):

&lt;template&gt;
  &lt;child :name='name'/&gt;  
&lt;/template&gt;
&lt;script setup&gt;
    import {ref} from 'vue'
    // Introduce subcomponents    import child from './'
    let name= ref('Tinker Bell')
&lt;/script&gt;

8. Use of parent value of emit child

The subcomponent code is as follows (example):

&lt;template&gt;
   &lt;a-button @click="isOk"&gt;
     Sure
   &lt;/a-button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { defineEmits } from 'vue';
// emit
const emit = defineEmits(['aboutExeVisible'])
/**
  * method
  */
// Click the OK buttonconst isOk = () =&gt; {
  emit('aboutExeVisible');
}
&lt;/script&gt;

The parent component code is as follows (example):

&lt;template&gt;
  &lt;AdoutExe @aboutExeVisible="aboutExeHandleCancel" /&gt;
&lt;/template&gt;
&lt;script setup&gt;
import {reactive} from 'vue'
// Import subcomponentsimport AdoutExe from '../components/AdoutExeCom'
const data = reactive({
  aboutExeVisible: false, 
})
// content component ref// About system hidingconst aboutExeHandleCancel = () =&gt; {
   = false
}
&lt;/script&gt;

9. Get the child component ref variable and defineExpose exposure

That is, the method to obtain the ref of the child component in vue2 and directly control the child component methods and variables in the parent component.

The subcomponent code is as follows (example):

&lt;template&gt;
    &lt;p&gt;{{data }}&lt;/p&gt;
&lt;/template&gt;
&lt;script setup&gt;
import {
  reactive,
  toRefs
} from 'vue'
/**
  * Data section
  * */
const data = reactive({
  modelVisible: false,
  historyVisible: false, 
  reportVisible: false, 
})
defineExpose({
  ...toRefs(data),
})
&lt;/script&gt;

The parent component code is as follows (example):

&lt;template&gt;
    &lt;button @click="onClickSetUp"&gt;Click&lt;/button&gt;
    &lt;Content ref="content" /&gt;
&lt;/template&gt;
&lt;script setup&gt;
import {ref} from 'vue'
// content component refconst content = ref('content')
// Click Settingsconst onClickSetUp = ({ key }) =&gt; {
    = true
}
&lt;/script&gt;
&lt;style scoped lang="less"&gt;
&lt;/style&gt;

10. Use of routes to useRoute and us eRouter

The code is as follows (example):

&lt;script setup&gt;
  import { useRoute, useRouter } from 'vue-router'
  // Statement  const route = useRoute()
  const router = useRouter()
  // Get query  ()
  // Get params  ()
  // Routing jump  ({
      path: `/index`
  })
&lt;/script&gt;

11. Use of the store warehouse

The code is as follows (example):

&lt;script setup&gt;
  import { useStore } from 'vuex'
  import { num } from '../store/index'
  const store = useStore(num)
  // Get Vuex's state  ()
  // Get Vuex getters  ()
  // Submit mutations  ('fnName')
  // Methods for distributing actions  ('fnName')
&lt;/script&gt;

12. Await's support

setup  You can use  await directly in syntax sugar, and there is no need to write async  .  setup will automatically become  async setup

The code is as follows (example):

<script setup>
  import api from '../api/Api'
  const data = await ()
  (data)
</script>

13. Provide and inject the value of grandparents and grandchildren

The parent component code is as follows (example)

&lt;template&gt;
  &lt;AdoutExe /&gt;
&lt;/template&gt;
 
&lt;script setup&gt;
  import { ref,provide } from 'vue'
  import AdoutExe from '@/components/AdoutExeCom'
 
  let name = ref('Jerry')
  // Use provide  provide('provideState', {
    name,
    changeName: () =&gt; {
       = 'Tinker Bell'
    }
  })
&lt;/script&gt;
The subcomponent code is as follows(Example):
&lt;script setup&gt;
  import { inject } from 'vue'
  const provideState = inject('provideState')
 
  ()
&lt;/script&gt;

The above is the detailed content shared by the tutorial on using setup syntax sugar in Vue 3.2. For more information about Vue setup syntax sugar, please follow my other related articles!