This is the fourth day of my participation in the First Challenge 2022

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

Writing in the front

When we wrote Vue2, we used Options API to write components, which is characterized by writing corresponding function modules in corresponding attributes, such as defining data in data and methods defining methods. The downside of this approach is that the code logic of the same function is split into attributes, affecting the code reading.

Vue3 provides the Composition API to help us organize our code elegantly and organize the code of related functions in a more orderly way. Please refer to “Making animation all night for a better understanding of Vue3’s Composition API”. The Composition API was animated.

Let’s take a look at how to write code using the Composition API.

Note: This article is all introduced and written in a < Script setup> manner. The advantage of this writing is that what is defined in < Script Setup > can be used directly in the template.

Responsive data

Creating reactive data in Vue3 is primarily done through the REACTIVE and REF apis, so let’s take a look at those and related apis in turn.

reactive

The Reactive API is used to create reactive objects or arrays, which are actually implemented internally by es6-based proxies.

The following code shows how the Reactive API is used:

<template>
  <h3>Information display component</h3>
  <div style="margin: 24px 0">
    <span>Name:</span>
    <span>{{ data.name }}</span>
    <br />
    <span>Age:</span>
    <span>{{ data.age }}</span>
  </div>
  <button @click="Data. name = 'week of a bowl '">Modify the name</button>
  <br />
  <button @click="data.age = '20'">Modify the age</button>
</template>
<script setup>/ / use<script setup>All apis need to be introduced separately, except Vue32.Automatic introduction of several apis.import { reactive } from 'vue'
// Create a responsive object
const data = reactive({
  name: 'A bowl of porridge'.age: '18',})</script>

Copy the code

The running results are as follows:

An isReactive API is also provided with Vue, which is used to detect whether a reactive agent has been created for Reactive.

Ref API

Reactive can only hijack Object or Array data. If we want to hijack ordinary data, we can use the REF API, for example:

<template>
  <h3>Information display component</h3>
  <div style="margin: 24px 0">
    <span>Name:</span>
    <! In the template, Vue will automatically unpack the ref, so we don't need to use the ref.value form -->
    <span>{{ name }}</span>
    <br />
    <span>Age:</span>
    <span>{{ age }}</span>
  </div>
  <button @click="handleEditName">Modify the name</button>
  <br />
  <button @click="handleEditAge">Modify the age</button>
</template>
<script setup>
/ / import ref
import { ref } from 'vue'
// Create a responsive object
const name = ref('A bowl of porridge')
const age = ref('18')
const handleEditName = () = > {
  // The reactive object created by ref needs to be accessed by ref.value
  name.value = 'Bowl Week'
}
const handleEditAge = () = > {
  age.value = '20'
}
</script>

Copy the code

The code runs the same as above.

readonly

Sometimes when we want to pass data to other components, we want the other components to use what we pass, but we don’t allow them to modify it. In this case, we can use the ReadOnly API, which creates an immutable object.

Let’s look at the following code:

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

When you change name, the value of readonlyName changes, but changing readonlyName directly does not take effect.

ToRefs and toRef

ToRefs and toRef are used to deconstruct reactive code created by Reactive into reactive data; If deconstructed directly using ES6 syntax, the deconstructed data is not responsive.

For example, the following code:

import { toRefs, reactive } from 'vue'
const user = reactive({ name: 'A bowl of porridge'.age: '18' })
// Attributes under user are linked to the deconstructed data through toRefs, and any modification causes changes to the other
const { name, age } = toRefs(user)
const handleEditName = () = > {
  name.value = 'Bowl Week'
}
const handleEditAge = () = > {
  age.value = '20'
}
Copy the code

If you want to deconstruct a single piece of data you can use toRef, as shown in the following code:

const name = toRef(user, 'name')
const age = toRef(user, 'age')
Copy the code

Calculate attribute

The definition of computed properties in the Composition API is implemented using a computed method that takes two parameters, a getter function and an object containing the get and set functions. Computed returns a REF object.

The following code shows the use of computed properties when receiving getters:

import { ref, computed } from 'vue'
const name = ref('Bowl Week')
const age = ref('18')
// Define computed properties
const user = computed(() = > {
  return ` name:${name.value}\ n age:${age.value}`
})
Copy the code

In the code above, when name or age changes, the user changes as well.

When a computed method accepts object parameters, the most common scenario is for a component to implement v-Model functionality, as shown in the following code:

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

Copy the code

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

The listener

The Composition API of Vue3 provides two apis for listening for changes in data, watchEffect (watchPostEffect and watchSyncEffect apis were added in Vue3 3.2, both nicknames for watchEffect. With specified options) and Watch, the differences are as follows:

  • WatchEffect dependencies for automatic collection of responsive data;
  • Watch needs to manually specify the data source to listen to;

The life cycle

Vue3’s composition API does not have lifecycle hook options, but provides onBeforeMount, onMounted and other functions to register periodic hook declarations.

Option type API Hook inside setup trigger
beforeMount onBeforeMount Triggered before component mount
mounted onMounted Trigger after component is mounted
beforeUpdate onBeforeUpdate Triggered before component update
updated onUpdated Triggered after component update
beforeUnmount onBeforeUnmount Triggered before component uninstallation
unmounted onUnmounted Triggered after component uninstallation

The following code shows some of the API usage:

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

Ref ($refs)

This.$refs is not available because Vue3’s composition API does not use this. How do we get components or elements? We need to define a ref object with the same name as the ref attribute in the template.

Example code is as follows:

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

})
</script> Copy the code

Write in the last

When you get used to the Composition API, it’s actually better than the Options API. This article is a primer on the Composition API. Simple usage and complex usage details are detailed in the Vue documentation