[Getting started with Vue2+3 to practice] (22) VUE3’s combined API - detailed explanation of setup, reactive and ref functions, computed, watch, and life cycle functions

Insert image description here

1. Combined API - setup option

1. How to write the setup option and when to execute it

Writing method

<script>
  export default {
    setup(){
      
    },
    beforeCreate(){
      
    }
  }
</script>

execution timing

Executed before beforeCreate hook

Insert image description here

2. Features of writing code in setup

The data and methods written in the setup function need to be returned in the form of objects at the end before they can be used by the template.

<script>
  export default {
    setup(){
      const message = 'this is message'
      const logMessage = ()=>{
        console.log(message)
      }
      // 必须return才可以
      return {
        message,
        logMessage
      }
    }
  }
</script>

3.

Add a setup tag to the script tag. There is no need to write an export statement. The export statement will be added by default.

<script setup>
  const message = 'this is message'
  const logMessage = ()=>{
    console.log(message)
  }
</script>

2. Combined API - reactive and ref functions

1. reactive

Accepts parameters of object type data and returns a responsive object

<script setup>
 // 导入
 import { reactive } from 'vue'
 // 执行函数 传入参数 变量接收
 const state = reactive({
   msg:'this is msg'
 })
 const setSate = ()=>{
   // 修改数据更新视图
   state.msg = 'this is new msg'
 }
</script>

<template>
  {
   
   { state.msg }}
  <button @click="setState">change msg</button>
</template>

2. ref

Receives data of simple type or object type and returns a responsive object

<script setup>
 // 导入
 import { ref } from 'vue'
 // 执行函数 传入参数 变量接收
 const count = ref(0)
 const setCount = ()=>{
   // 修改数据更新视图必须加上.value
   count.value++
 }
</script>

<template>
  <button @click="setCount">{
   
   {count}}</button>
</template>

3. reactive vs ref

  1. are used to generate responsive data
  2. difference
    1. Reactive cannot handle simple types of data
    2. The ref parameter type has better support, but access modification must be done through .value
    3. The implementation inside the ref function depends on the reactive function
  3. Recommendations in actual work
    1. It is recommended to use the ref function to reduce the memory burden. All Xiaotuxian projects use ref.

3. Combined API - computed

The basic idea of ​​calculated properties is consistent with Vue2. The calculated properties under the combined API only modify the API writing method.

<script setup>
// 导入
import {ref, computed } from 'vue'
// 原始数据
const count = ref(0)
// 计算属性
const doubleCount = computed(()=>count.value * 2)

// 原始数据
const list = ref([1,2,3,4,5,6,7,8])
// 计算属性list
const filterList = computed(item=>item > 2)
</script>

4. Combined API - watch

Listen for changes in one or more data, execute the callback function when the data changes, the two additional parameters immediate control to execute immediately, and deep enables in-depth listening

1. Listen to a single data

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  // 2. 调用watch 侦听变化
  watch(count, (newValue, oldValue)=>{
    console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
  })
</script>

2. Listen to multiple data

To listen to multiple data, the first parameter can be rewritten as an array.

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  const name = ref('cp')
  // 2. 调用watch 侦听变化
  watch([count, name], ([newCount, newName],[oldCount,oldName])=>{
    console.log(`count或者name变化了,[newCount, newName],[oldCount,oldName])
  })
</script>

3. immediate

The callback is triggered immediately when the listener is created, and the callback is continued after the responsive data changes.

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  // 2. 调用watch 侦听变化
  watch(count, (newValue, oldValue)=>{
    console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
  },{
    immediate: true
  })
</script>

4. deep

The ref object monitored through watch is shallow listening by default. Directly modifying the nested object properties will not trigger callback execution. You need to enable deep

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const state = ref({ count: 0 })
  // 2. 监听对象state
  watch(state, ()=>{
    console.log('数据变化了')
  })
  const changeStateByCount = ()=>{
    // 直接修改不会引发回调执行
    state.value.count++
  }
</script>

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const state = ref({ count: 0 })
  // 2. 监听对象state 并开启deep
  watch(state, ()=>{
    console.log('数据变化了')
  },{deep:true})
  const changeStateByCount = ()=>{
    // 此时修改可以触发回调
    state.value.count++
  }
</script>

5. Combined API - life cycle function

1. Option vs. Combination

Insert image description here

2. Basic use of life cycle functions

  1. Import life cycle functions
  2. Execute the life cycle function and pass in the callback
<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{
  // 自定义逻辑
})
</script>

3. Execute multiple times

When the life cycle function is executed multiple times, it will be executed in sequence.

<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{
  // 自定义逻辑
})

onMounted(()=>{
  // 自定义逻辑
})
</script>

6. Summary

The composition API is a new feature in Vue3, which allows us to write component logic in a more flexible and composable way.

  1. setup function : The setup function is the entrance to the combined API. It is called before the component instance is created. We can perform some initialization logic in the setup function and return an object, which will become a property of the component instance. The setup function receives two parameters: props and context. Props are properties of the component. Context provides some commonly used APIs, such as emit for dispatching events.

  2. Reactive and ref functions : The reactive function receives a normal object and returns a reactive proxy object. The ref function takes a normal value and returns a reactive reference object. We can use reactive and ref functions to create responsive data. Reactive data can be used in templates and their dependencies can be tracked automatically.

  3. computed function : The computed function receives a getter function and returns a computed property. A computed property is a reactive object that automatically tracks its dependencies and recalculates them when the dependencies change. We can use the computed function to handle some complex data logic, such as operating on multiple responsive data to obtain a new value.

  4. watch function : The watch function is used to monitor changes in responsive data and perform some side effects when the data changes. The watch function receives two parameters: the responsive data to be monitored and the callback function. We can use the watch function to handle some asynchronous operations, such as sending network requests or saving data.

  5. Lifecycle functions : The lifecycle functions in Vue3 have undergone some changes. In the setup function, you can use functions such as onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount and onUnmounted to replace the life cycle hook function in Vue2. These functions are called before the component is mounted, after mounting, before updating, after updating, before uninstalling, and after uninstalling. We can perform some operations related to the component life cycle in these functions, such as requesting data, adding event listeners, etc.

To sum up, Vue3's composed API provides a more flexible and composable way to write component logic, allowing us to better organize and reuse code. It uses some new functions and concepts, such as setup function, reactive and ref functions, computed function, watch function and new life cycle function. By learning and mastering these APIs, we can develop Vue3 applications more efficiently.

Guess you like

Origin blog.csdn.net/shenchengyv/article/details/135375601