当前位置:网站首页>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
边栏推荐
- The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!
- Iclr2022 | spherenet and g-spherenet: autoregressive flow model for 3D molecular graph representation and molecular geometry generation
- No converter found for return value of type: class
- PLC Analog input analog conversion FB s_ ITR (Mitsubishi FX3U)
- Recently, three articles in the nature sub Journal of protein and its omics knowledge map have solved the core problems of biology
- Global and Chinese market of picture archiving and communication system (PACS) 2022-2028: Research Report on technology, participants, trends, market size and share
- Appium inspector can directly locate the WebView page. Does anyone know the principle
- 8.8.4-PointersOnC-20220215
- 笔者更加愿意将产业互联网看成是一个比消费互联网要丰富得多的概念
- Learn C language from scratch day 025 (maze)
猜你喜欢

How can I batch produce the same title for the video?

学习笔记25--多传感器前融合技术

学习笔记3--高精度地图关键技术(上)

Data visualization in medical and healthcare applications

GL Studio 5 安装与体验

Recommend an online interface mock tool usemock

Docker installing Oracle_ 11g

The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!

首场“移动云杯”空宣会,期待与开发者一起共创算网新世界!

How to compress video size while adding watermark with one click?
随机推荐
[IVX junior engineer training course 10 papers] 06 database and services
Docker installing Oracle_ 11g
Global and Chinese markets for the application of artificial intelligence in security, public security and national security 2022-2028: Research Report on technology, participants, trends, market size
Bubble Sort Graph
Exclusive delivery of secret script move disassembly (the first time)
Liteos learning - first knowledge of development environment
Minimize the error
6-3漏洞利用-SSH环境搭建
Just using the way and method of consuming the Internet to land and practice the industrial Internet will not bring long-term development
Fastadmin controls the length of fields in the table
[IVX junior engineer training course 10 papers to get certificates] 03 events and guessing numbers games
MySQL application day02
Geek DIY open source solution sharing - digital amplitude frequency equalization power amplifier design (practical embedded electronic design works, comprehensive practice of software and hardware)
[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)
Datawhale community blackboard newspaper (issue 1)
Leetcode, 3 repeatless longest subsequence
We should make clear the branch prediction
【图像增强】基于Frangi滤波器实现血管图像增强附matlab代码
The author is more willing to regard industrial Internet as a concept much richer than consumer Internet
Deb file installation