当前位置:网站首页>10 minutes to get started quickly composition API (setup syntax sugar writing method)
10 minutes to get started quickly composition API (setup syntax sugar writing method)
2022-07-02 01:20:00 【A bowl of weeks】
Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~
Write it at the front
We're writing Vue2 When , The way to write components is to use Options API, This way is characterized by Write corresponding function modules for corresponding attributes , For example, in data Data defined in 、methods Define methods, etc ; The disadvantage of this method is The code logic of the same function is split into various attributes , Affect code reading .
Vue3 Provided in Composition API It can help us organize our code gracefully , Make the code of related functions more orderly organized together , You can refer to 『 Did a night of animation , Just to make you understand better Vue3 Of Composition Api』, It uses animation to explain Composition API.
Next, let's introduce how to adopt Composition API How to write code .
notes : This article is all based on
<script setup>Method introduction and compilation of , The advantage of writing like this is that<script setup>The content defined in can be used directly in the template .
Responsive data
stay Vue3 Creating responsive data in is mainly through reactive and ref these two items. API Realized , Now let's learn these two and related API.
reactive
reactive API Used to create responsive objects or arrays , In fact, the internal of this method is based on ES6 Of Proxy Realized .
The following code shows reactive API Usage of :
<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 '"> Change the name </button>
<br />
<button @click="data.age = '20'"> Change the age </button>
</template>
<script setup> // Use <script setup> be-all API Need to be introduced separately , except Vue3.2 Several automatically introduced API Outside . import {
reactive } from 'vue' // Create responsive objects const data = reactive({
name: ' A cup of porridge ', age: '18', }) </script>
The operation results are as follows :

Vue There is also a isReactive, The API Used to detect whether it is reactive Create a responsive proxy for .
Ref API
We use reactive Only right Object perhaps Array Type of data , If we want to hijack data of ordinary data types , have access to ref API, For example, 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 for ref Unpack , So you don't need to use it ref.value In the form of -->
<span>{
{ name }}</span>
<br />
<span> Age :</span>
<span>{
{ age }}</span>
</div>
<button @click="handleEditName"> Change the name </button>
<br />
<button @click="handleEditAge"> Change the age </button>
</template>
<script setup> // Import ref import {
ref } from 'vue' // Create responsive objects const name = ref(' A cup of porridge ') const age = ref('18') const handleEditName = () => {
// adopt ref Create responsive objects , We need to pass ref.value Mode of access name.value = ' A bowl week ' } const handleEditAge = () => {
age.value = '20' } </script>
The result of code running is the same as above .
readonly
Sometimes we want to pass data to other components , We often want other components to use what we pass , But they are not allowed to modify , It can be used at this time readonly API, The API You can create a non modifiable object .
Let's look at the following code :
import { ref, readonly } from 'vue'
// Create responsive objects
const name = ref(' A cup of porridge ')
const age = ref('18')
const readonlyName = readonly(name)
const handleEditName = () => {
// adopt ref Create responsive objects , We need to pass ref.value Mode of access
name.value = ' A bowl week '
}
const handleEditAge = () => {
age.value = '20'
}
We modify name when ,readonlyName The value of will change accordingly , But modify it directly readonlyName It doesn't work .
toRefs and toRef
toRefs and toRef Is used to reactive The created responsive code solution constitutes responsive data ; If used directly ES6 Deconstruct the grammar of , 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' })
// user Attributes under pass toRefs Links to the deconstructed data , Any change 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 individual data, you can use toRef, The sample code is as follows :
const name = toRef(user, 'name')
const age = toRef(user, 'age')
Compute properties
stay Composition API The calculation attribute is defined in computed Method realization , It can accept two parameters , One is getter function , The other is to include get and set Object of function ;computed Return to one ref object .
The following code shows receiving getter Function time , Use of calculated properties :
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 name perhaps age When something changes ,user Will also change .
computed Method accepts object parameters , The most common scenario is component implementation v-model The function of , The sample code is as follows :
<template>
<input type="text" v-model="myName" />
</template>
<script setup> // Introduce the required methods import {
defineProps, defineEmits, computed } from 'vue' // Definition props const props = defineProps({
name: String, }) // v-model Prescriptive writing update:name name-> need v-model The name of 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 computed Method to pass object parameters .
Monitor
Vue3 Of composition API Two for monitoring data changes are provided in API, Namely watchEffect(Vue3.2 Added in watchPostEffect and watchSyncEffect API, These are both watchEffect Another name for , With specified options ) and watch, The difference between the two is as follows :
watchEffectDependencies for automatically collecting responsive data ;watchYou need to manually specify the data source to listen to ;
Life cycle
Vue3 Of composition API There is no lifecycle hook option , But it offers onBeforeMount、onMounted And other functions to register the declaration cycle hook , The provided declaration periodic function is shown in the following table :
| Optional API | Hook inside setup | trigger |
|---|---|---|
beforeMount | onBeforeMount | Trigger before component mount |
mounted | onMounted | Trigger after the component is mounted |
beforeUpdate | onBeforeUpdate | Triggered before component update |
updated | onUpdated | Triggered after component update |
beforeUnmount | onBeforeUnmount | Triggered before the component is unloaded |
unmounted | onUnmounted | Triggered after the component is unloaded |
The following code shows some API Usage of :
import { onMounted, onUpdated, onUnmounted } from 'vue'
onMounted(() => {
console.log('onMounted')
})
onUpdated(() => {
console.log('onUpdated')
})
onUnmounted(() => {
console.log('onUnmounted')
})
Templates ref($refs A substitute for )
because Vue3 Of composition API Can't use this, So this.$refs Do not use , How can we get components or elements ? It's very simple , We need to define ref object , Name and template ref The names of attributes should be consistent .
The sample 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>
At the end
I'm used to writing composition API after , Do than Options API To use . This article introduces some simple usage , Complex usage and details are actually Vue The document is very detailed , This article is mainly about getting started composition API
边栏推荐
- Learning note 24 - multi sensor post fusion technology
- MySQL winter vacation self-study 2022 12 (4)
- SQL injection for Web Security (2)
- [dynamic planning] interval dp:p3205 Chorus
- The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!
- GL Studio 5 安装与体验
- How to compress video size while adding watermark with one click?
- MySQL application day02
- Basic number theory -- Gauss elimination
- Look at the industrial Internet from a new perspective and seek the correct ways and methods of industrial Internet
猜你喜欢

Edge computing accelerates live video scenes: clearer, smoother, and more real-time
![[IVX junior engineer training course 10 papers to get certificates] 01 learn about IVX and complete the New Year greeting card](/img/99/53b0ae47bada8b0d4db30d0517fe3d.jpg)
[IVX junior engineer training course 10 papers to get certificates] 01 learn about IVX and complete the New Year greeting card

Review notes of compilation principles

【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)

How to compress video size while adding watermark with one click?

【图像增强】基于Frangi滤波器实现血管图像增强附matlab代码

6-3 vulnerability exploitation SSH environment construction
![[IVX junior engineer training course 10 papers] 02 numerical binding and adaptive website production](/img/b7/aecb815ca9545981563a1e16cfa19e.jpg)
[IVX junior engineer training course 10 papers] 02 numerical binding and adaptive website production

Day 13 of hcip (relevant contents of BGP agreement)

Creating logical volumes and viewing and modifying attributes for AIX storage management
随机推荐
Global and Chinese markets for maritime services 2022-2028: Research Report on technology, participants, trends, market size and share
ACM教程 - 快速排序(常规 + 尾递归 + 随机基准数)
[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)
The author is more willing to regard industrial Internet as a concept much richer than consumer Internet
Docker installing Oracle_ 11g
A problem about function template specialization
[IVX junior engineer training course 10 papers] 06 database and services
[image enhancement] vascular image enhancement based on frangi filter with matlab code
电商系统中常见的9大坑,你踩过没?
[IVX junior engineer training course 10 papers] 05 canvas and aircraft war game production
How does schedulerx help users solve the problem of distributed task scheduling?
Just using the way and method of consuming the Internet to land and practice the industrial Internet will not bring long-term development
Global and Chinese market of avionics systems 2022-2028: Research Report on technology, participants, trends, market size and share
[Chongqing Guangdong education] Tianshui Normal University universe exploration reference
cookie、session、tooken
Excel search and reference function
游戏思考15:全区全服和分区分服的思考
MySQL application day02
学习笔记24--多传感器后融合技术
ACM tutorial - quick sort (regular + tail recursion + random benchmark)