Quick start vue3 composition API

(Creating is not easy, thank you, your support is the biggest motivation for me to move forward, if it is helpful to you after reading it, please leave your footprints)

Create a project using create-vue

1. Prerequisite environmental conditions
Node.js version 16.0 or later installed
node -v
2. Create a Vue application
npm init vue@latest
This command will install and execute create-vue

Familiarize yourself with the project directory and key files 

Key files:
1. vite.config.js - The configuration file of the project is based on the configuration of vite
2. package.json - The core dependencies of the project package file become Vue3.x and vite
3. main.js - the entry file createApp function creates an application instance
4. app.vue - root component SFC single file component script - template - style
        Change 1: Adjust the order of script script and template template
        Change 2: The template template no longer requires a unique root element
        Change 3: Script script adds setup flag to support combined API
5. index.html - The single-page entry provides the mount point with the id as app

Composite API 

setup option

The writing method and execution timing of the setup option

    

1. The timing of execution is earlier than beforeCreate

2. In the setup function, this cannot be obtained (this is undefined)

<script> 
// setup
// 1. 执行时机,比beforeCreate还要早
// 2. setup函数中,获取不到this (this是undefined)
export default {
  setup () {
    console.log('setup函数',this)
  },
  beforeCreate () {
    console.log('beforeCreate函数')
  }
}
</script>

The web page appears as:                                                 

3. Data and functions need to be returned at the end of the setup before they can be applied in the template

<script> 
export default {
  setup () {
    // 数据
    const message = 'hello Vue3'
    // 函数
    const logMessage = () => {
      console.log(message)
    }
    return {
      message,
      logMessage
    }
  }
}
</script>

<template>
  <div>{
   
   { message }}</div>
  <button @click="logMessage">按钮</button>
</template>

<script setup> syntactic sugar

Question: I have to return every time, so troublesome?

4. Simplify code through setup syntactic sugar

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

<template>
  <div>{
   
   { message }}</div>
  <button @click="logMessage">按钮</button>
</template>

reactive and ref functions

reactive()

Function: Accept the parameter input of object type data and return a responsive object
Core steps:
1. Import the reactive function from the vue package
2. Execute the reactive function in <script setup> and pass in the initial value of type object , and use the variable to receive the return value
<script setup>
//1. reactive: 接收一个对象类型的数据,返回一个响应式的对象
import { reactive } from 'vue'
const state = reactive({
  count: 100
})
const setCount = () => {
  state.count++
}

</script>

<template>
  <div>
    <div>{
   
   { state.count }}</div>
    <button @click="setCount">+1</button>
  </div>
</template>

ref()

Function: Receive simple type or object type data input and return a responsive object

Essence: On the basis of the original incoming data, a layer of objects is wrapped in the outer layer, and it is wrapped into a complex type

           The bottom layer, after being packaged into complex types, is then implemented with the help of reactive

important point:

           1. To access data in the script, you need to pass .value

           2. In the template, .value does not need to be added (help us pick up a layer)

Core steps:

1. Import the ref function from the vue package
2. Execute the ref function in <script setup> and pass in the initial value, and use the variable to receive the return value of the ref function
<script setup>
import { ref } from 'vue'
const count = ref(0)
const setCount = () => {
  count.value++
}
</script>

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

computed

The basic idea of ​​calculated properties is exactly the same as that of Vue2, and the calculated properties under the combined API are just modified.
Core steps: 1. Import the computed function
2. The execution function returns the calculated value based on the responsive data in the callback parameter , and receives it with a variable
<script setup>
import{computed,ref}from 'vue'
const list=ref([1,2,3,4,5,6,7,8])
const computedList = computed(()=>{
  return list.value.filter(item=>item>2)
})
</script>

<template>
  <div>
    <div>原始数据: {
   
   { list }}</div>
    <div>计算后的数据: {
   
   { computedList }}</div>
  </div>
</template>a

watch

Function: Listen to the change of one or more data , and execute the callback function when the data changes
Two additional parameters: 1. immediate (immediate execution) 2. deep (deep listening)

listen for single data

1. Import watch function
2. Execute the watch function to pass in the responsive data (ref object) and callback function to be listened to

Listen for multiple data 

Listen to multiple responsive data changes at the same time, no matter which data changes, you need to execute the callback

immediate 

Trigger the callback immediately when the listener is created , and continue to execute the callback after the responsive data changes

deep

The ref object monitored by watch is shallow by default. Modifying the nested object properties directly will not trigger the callback execution . The deep option needs to be enabled.
<script setup>
import{watch,ref}from 'vue'
// 4. deep 深度监视, 默认 watch 进行的是 浅层监视
//    const ref1 = ref(简单类型) 可以直接监视
//    const ref2 = ref(复杂类型) 监视不到复杂类型内部数据的变化
const userInfo = ref({
  name: 'zs',
  age: 18
})
const setUserInfo = () => {
  // 修改了 userInfo.value 修改了对象的地址,才能监视到
  // userInfo.value = { name: 'ls', age: 50 }
  userInfo.value.age++
}

// deep 深度监视
watch(userInfo, (newValue) => {
  console.log(newValue)
}, {
  deep: true
})
</script>

<template>
  <div>{
   
   { userInfo }}</div>
  <button @click="setUserInfo">修改userInfo</button>
</template>a

Accurately listen to a property of an object 

Under the premise of not turning on deep, listen to the change of age, and only execute the callback when the age changes
<script setup>
import{watch,ref}from 'vue'
// 4. deep 深度监视, 默认 watch 进行的是 浅层监视
//    const ref1 = ref(简单类型) 可以直接监视
//    const ref2 = ref(复杂类型) 监视不到复杂类型内部数据的变化
const userInfo = ref({
  name: 'zs',
  age: 18
})
const setUserInfo = () => {
  // 修改了 userInfo.value 修改了对象的地址,才能监视到
  // userInfo.value = { name: 'ls', age: 50 }
  userInfo.value.age++
}

// 5. 对于对象中的单个属性,进行监视
watch(() => userInfo.value.age, (newValue, oldValue) => {
  console.log(newValue, oldValue)
})
</script>

<template>
  <div>{
   
   { userInfo }}</div>
  <button @click="setUserInfo">修改userInfo</button>
</template>

life cycle function

Vue3's Lifecycle API (Optional VS Composition)

father-son communication 

Parent-to-child transfer under combined API

basic idea
1. Bind attributes to child components in the parent component
2. The subcomponent receives it through the props option

The principle of defineProps: It is an identifier in the compilation phase. When the actual compiler parses, it will compile and convert when it encounters it

Passing from child to parent under combined API 

basic idea
1. In the parent component, label the child component through @binding event
2. The event is triggered inside the subcomponent through the emit method

template reference 

How to use (Take DOM as an example for components)

Get the real dom object or component instance object through ref identification

1. Call the ref function to generate a ref object
2. Bind the ref object to the label through the ref identifier

defineExpose() 

By default, the properties and methods inside the component under the syntactic sugar of <script setup> are not open to the parent component for access.
You can specify which properties and methods are allowed to be accessed by compiling the macro through defineExpose

Guess you like

Origin blog.csdn.net/weixin_73295475/article/details/132277906