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~