Vue3.2 setup syntax sugar summary

Vue3.2 setup syntax sugar summary

In Vue3.2, simply add the setup attribute to the script tag, no need to return, and the template can be used directly. It's really awesome!

Last updated 5/19/2022 6:47 AM
玲小叮当
6 min read
Category
Frontend
Tags
Vue

Preface

Note: Syntax sugar is only available from Vue 3.2 onwards!

In Vue 3.0, variables must be returned to be used in template; in Vue 3.2, you only need to add the setup attribute to the script tag, no return is required, and template can directly use them, which is very convenient!

Note: The following is the main content of this article, and the cases below can be used as references.

1. How to Use the setup Syntax Sugar

Simply write setup on the script tag.

Code example:

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

2. Using data

Since setup does not require writing return, you can declare data directly.

Code example:

<script setup>
    import {
      ref,
      reactive,
      toRefs,
    } from 'vue'

    const data = reactive({
      patternVisible: false,
      debugVisible: false,
      aboutExeVisible: false,
    })

    const content = ref('content')
    // Destructure using toRefs
    const { patternVisible, debugVisible, aboutExeVisible } = toRefs(data)
</script>

3. Using Methods

Code example:

<template >
    <button @click="onClickHelp">System Help</button>
</template>
<script setup>
import {reactive} from 'vue'

const data = reactive({
      aboutExeVisible: false,
})
// Click help
const onClickHelp = () => {
    console.log(`System Help`)
    data.aboutExeVisible = true
}
</script>

4. Using watchEffect

Code example:

<script setup>
import {
  ref,
  watchEffect,
} from 'vue'

let sum = ref(0)

watchEffect(()=>{
  const x1 = sum.value
  console.log('watchEffect callback executed')
})
</script>

5. Using watch

Code example:

<script setup>
    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 watch formats
    watch([sum,msg],(newValue,oldValue)=>{
            console.log('sum or msg changed',newValue,oldValue)
          },{immediate:true})

     watch(()=>person.job,(newValue,oldValue)=>{
        console.log('person job changed',newValue,oldValue)
     },{deep:true})

</script>

6. Using Computed Properties

Computed properties have two forms (shorthand and full version with get/set).

Code example:

<script setup>
    import {
      reactive,
      computed,
    } from 'vue'

    // Data
    let person = reactive({
       firstName:'Little',
       lastName:'Ding Dang'
     })
    // Shorthand for computed
    person.fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
      })
    // Full version
    person.fullName = computed({
      get(){
        return person.firstName + '-' + person.lastName
      },
      set(value){
        const nameArr = value.split('-')
        person.firstName = nameArr[0]
        person.lastName = nameArr[1]
      }
    })
</script>

7. Using props for Parent-Child Communication

Child component code example:

<template>
  <span>{{props.name}}</span>
</template>

<script setup>
  import { defineProps } from 'vue'
  // Declare props
  const props = defineProps({
    name: {
      type: String,
      default: '11'
    }
  })
  // Or
  //const props = defineProps(['name'])
</script>

Parent component code example:

<template>
  <child :name='name'/>
</template>

<script setup>
    import {ref} from 'vue'
    // Import child component
    import child from './child.vue'
    let name= ref('Little Ding Dang')
</script>

8. Using emit for Child-Parent Communication

Child component code example:

<template>
   <a-button @click="isOk">
      Confirm
   </a-button>
</template>
<script setup>
import { defineEmits } from 'vue';

// emit
const emit = defineEmits(['aboutExeVisible'])
/**
 * Methods
 */
// Click confirm button
const isOk = () => {
  emit('aboutExeVisible');
}
</script>

Parent component code example:

<template>
  <AdoutExe @aboutExeVisible="aboutExeHandleCancel" />
</template>
<script setup>
import {reactive} from 'vue'
// Import child component
import AdoutExe from '../components/AdoutExeCom'

const data = reactive({
  aboutExeVisible: false,
})
// content component ref

// About system hide
const aboutExeHandleCancel = () => {
  data.aboutExeVisible = false
}

</script>

9. Getting Child Component ref and Exposing with defineExpose

This is the approach to get a child component's ref (as in Vue 2) and directly control the child component's methods and variables from the parent.

Child component code example:

<template>
    <p>{{data }}</p>
</template>

<script setup>
import {
  reactive,
  toRefs
} from 'vue'

/**
 * Data section
 * */
const data = reactive({
  modelVisible: false,
  historyVisible: false,
  reportVisible: false,
})
defineExpose({
  ...toRefs(data),
})
</script>

Parent component code example:

<template>
    <button @click="onClickSetUp">Click</button>
    <Content ref="content" />
</template>

<script setup>
import {ref} from 'vue'

// content component ref
const content = ref('content')
// Click setup
const onClickSetUp = ({ key }) => {
   content.value.modelVisible = true
}

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

10. Using useRoute and useRouter for Routing

Code example:

<script setup>
  import { useRoute, useRouter } from 'vue-router'

  // Declare
  const route = useRoute()
  const router = useRouter()

  // Get query
  console.log(route.query)
  // Get params
  console.log(route.params)

  // Route navigation
  router.push({
      path: `/index`
  })
</script>

11. Using the Store (Vuex)

Code example:

<script setup>
  import {useStore} from 'vuex'
  import {num} from '../store/index'
  const store = useStore(num)
  // Get Vuex state
  console.log(store.state.number)
  // Get Vuex getters
  console.log(store.state.getNumber)
  // Commit mutations
  store.commit('fnName')
  // Dispatch actions
  store.dispatch('fnName')
</script>

12. Supporting await

Inside the setup syntax sugar, you can directly use await without writing async. The setup will automatically become async setup.

Code example:

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

13. Using provide and inject for Ancestor-Descendant Communication

Parent component code example:

<template>
  <AdoutExe />
</template>

<script setup>
  import { ref,provide } from 'vue'
  import AdoutExe from '@/components/AdoutExeCom'

  let name = ref('Jerry')
  // Use provide
  provide('provideState', {
    name,
    changeName: () => {
      name.value = 'Little Ding Dang'
    }
  })
</script>

Child component code example:

<script setup>
  import {inject} from 'vue'
  const provideState = inject('provideState')
  provideState.changeName()
</script>

Summary

Note: The above summarizes my study of using setup syntax sugar through blogs and other resources. I have applied it in projects and it works. If I made any mistakes or used methods incorrectly, please let me know and I will correct them immediately! If you find my article useful, please feel free to like, bookmark, and follow. Follow the blogger and never get lost! I will continue to update when work is not busy. Welcome to check out my other articles~

Keep Exploring

Related Reading

More Articles
Same tag 11/6/2024

Why My Blog Website Returned to Blazor

The development of the blog website has gone through many hardships, with nearly 10 versions including MVC, Vue, Go, etc. Now it has returned to Blazor and adopted static SSR, resulting in a significant speed increase and successful launch.

Continue Reading
Same tag 10/16/2023

.NET Toolbox: Open-source, free pure frontend tool website, exploring 10 major tool categories and 73 real-time online gadgets

Dotnet Toolbox is a pure frontend, open-source, and free tool website. Over the weekend, I referred to the open-source project it-tools, localized the website interface text into Chinese, and redeployed the site. The website has 10 major tool categories and provides 73 real-time online gadgets. Developed with Vue3, the Dotnet Toolbox has unique features. This article details some of these featured tools and briefly shares how to deploy your own tool website. If you are interested in tool websites, why not come and learn about Dotnet Toolbox!

Continue Reading