10 minutes to get started with Composition API (setup syntax)

Posted by xatter on Mon, 14 Feb 2022 13:10:06 +0100

Hello, I'm A bowl week , a front end that doesn't want to be drunk. If you are lucky enough to get your favor, I am very lucky~

Write in front

When we write Vue2, the way to write components is to use the Options API. The feature of this way is to write corresponding function modules in the corresponding attributes, such as defining data in data and methods; The disadvantage of this method is that the code logic of the same function is split into various attributes, which affects the reading of the code.

The Composition API provided in Vue3 can help us organize our code gracefully and make the code of related functions more orderly. Please refer to I made an animation all night to make everyone better understand Vue3's Composition Api The Composition API is explained in the form of animation.

Next, let's introduce how to write code in the way of Composition API.

Note: This article is introduced and written based on < script setup >, which has the advantage that the content defined in < script setup > can be used directly in the template.

Responsive data

Creating responsive data in Vue3 is mainly realized through two APIs: reactive and ref. now let's learn these two APIs and related APIs in turn.

reactive

The reactive API is used to create responsive objects or arrays. In fact, the interior of this method is based on the Proxy implementation of ES6.

The following code shows the usage of the reactive API:

<template>
  <h3>Information display component</h3>
  <div style="margin: 24px 0">
    <span>full name:</span>
    <span>{{ data.name }}</span>
    <br />
    <span>Age:</span>
    <span>{{ data.age }}</span>
  </div>
  <button @click="data.name = 'A bowl week'">Modify name</button>
  <br />
  <button @click="data.age = '20'">Modify age</button>
</template>
<script setup>
// All APIs using < script setup > need to be introduced separately, except vue3 2. Several APIs introduced automatically.
import { reactive } from 'vue'
// Create a responsive object
const data = reactive({
  name: 'A cup of porridge',
  age: '18',
})
</script>

The operation results are as follows:

Vue also provides an isReactive API, which is used to detect whether a reactive proxy is created for reactive.

Ref API

Using reactive, we can only hijack data of Object or Array type. If we want to hijack data of ordinary data type, we can use ref API, such as the following code:

<template>
  <h3>Information display component</h3>
  <div style="margin: 24px 0">
    <span>full name:</span>
    <!-- In the template, Vue Will automatically help us ref Unpack, so you don't need to use ref.value Form of -->
    <span>{{ name }}</span>
    <br />
    <span>Age:</span>
    <span>{{ age }}</span>
  </div>
  <button @click="handleEditName">Modify name</button>
  <br />
  <button @click="handleEditAge">Modify age</button>
</template>
<script setup>
// Import ref
import { ref } from 'vue'
// Create a responsive object
const name = ref('A cup of porridge')
const age = ref('18')
const handleEditName = () => {
  // The responsive object created by ref needs to be accessed by ref.value
  name.value = 'A bowl week'
}
const handleEditAge = () => {
  age.value = '20'
}
</script>

The result of code running is the same as above.

readonly

Sometimes when we want to pass data to other components, we often want other components to use the content we pass, but they are not allowed to modify. At this time, we can use readonly API, which can create an object that cannot be modified.

Let's look at the following code:

import { ref, readonly } from 'vue'
// Create a responsive object
const name = ref('A cup of porridge')
const age = ref('18')
const readonlyName = readonly(name)
const handleEditName = () => {
  // The responsive object created by ref needs to be accessed by ref.value
  name.value = 'A bowl week'
}
const handleEditAge = () => {
  age.value = '20'
}

When we modify the name, the value of readonlyName will also change, but directly modifying readonlyName will not take effect.

toRefs and toRef

toRefs and toRef are used to decompose the responsive code created by reactive into responsive data; If you directly use the syntax of ES6 to deconstruct, the deconstructed data is not responsive.

For example, the following code:

import { toRefs, reactive } from 'vue'
const user = reactive({ name: 'A cup of porridge', age: '18' })
// The attribute under user is linked to the deconstructed data through toRefs. Any modification will cause another change
const { name, age } = toRefs(user)
const handleEditName = () => {
  name.value = 'A bowl week'
}
const handleEditAge = () => {
  age.value = '20'
}

If you want to deconstruct a single data, you can use toRef. The example code is as follows:

const name = toRef(user, 'name')
const age = toRef(user, 'age')

Calculation properties

The calculation attribute defined in the Composition API is implemented through the calculated method, which can accept two parameters: one is the getter function, and the other is the object containing the get and set functions; computed returns a ref object.

The following code shows the usage of calculating attributes when receiving getter function:

import { ref, computed } from 'vue'
const name = ref('A bowl week')
const age = ref('18')
// Define calculation properties
const user = computed(() => {
  return `full name: ${name.value}\n Age: ${age.value}`
})

In the above code, when the name or age changes, the user will also change.

When the calculated method accepts object parameters, the most common scenario is that the component implements the function of v-model. The example code is as follows:

<template>
  <input type="text" v-model="myName" />
</template>
<script setup>
// Introduce required methods
import { defineProps, defineEmits, computed } from 'vue'
// Define props
const props = defineProps({
  name: String,
})
// v-model specifies the writing method update: name - > requires the name of v-model
const emit = defineEmits(['update:name'])
// Define calculation properties
const myName = computed({
  get() {
    return props.name
  },
  set(val) {
    emit('update:name', val)
  },
})
</script>

The above code shows how to pass object parameters in the computed method.

monitor

Vue3's composition API provides two APIs for monitoring data changes, namely, watchEffect (Vue3.2 adds watchPostEffect and watchsynceffect APIs, which are aliases of watchEffect with specified options) and watch. The differences between the two are as follows:

  • watchEffect Dependencies for automatically collecting responsive data;
  • watch You need to manually specify the data source to listen to;

life cycle

Vue3's composition API does not have a life cycle hook option, but provides onBeforeMount, onMounted and other functions to register the declaration cycle hook. The provided declaration cycle functions are shown in the following table:

Optional APIHook inside setupTrigger timing
beforeMountonBeforeMountTriggered before component mount
mountedonMountedTriggered after the component is mounted
beforeUpdateonBeforeUpdateTriggered before component update
updatedonUpdatedTriggered after component update
beforeUnmountonBeforeUnmountTriggered before component unloading
unmountedonUnmountedTriggered after component unloading

The following code shows the usage of some API s:

import { onMounted, onUpdated, onUnmounted } from 'vue'
onMounted(() => {
  console.log('onMounted')
})
onUpdated(() => {
  console.log('onUpdated')
})
onUnmounted(() => {
  console.log('onUnmounted')
})

Template ref ($a substitute for refs)

Because Vue3's composition API cannot use this, it is called this$ Refs can't be used. How can we get components or elements? In fact, it is very simple. We need to define a ref object whose name is consistent with that of the ref attribute in the template.

The example code is as follows:

<template>
  <h3 ref="nameRef">A bowl week</h3>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const nameRef = ref(null)
onMounted(() => {
  console.log(nameRef.value) // <h3>A bowl week</h3>
})
</script>

Write at the end

After getting used to writing composition API, it is really easier to use than Options API. This article introduces some simple usage, complex usage and details. In fact, Vue documents are very detailed. This article is mainly about the introduction of composition API

Topics: Javascript Front-end Vue.js