Vue3.2 was released a while ago, so for front-line front-end engineers, it’s worth upgrading VUE2 to VUE3 to embrace the new Composition API?

Install the latest @vue/ CLI

npm install -g @vue/cli
Copy the code

Then use the command line

Vue create hello-vue3 Project nameCopy the code
<template>
  <div>
      <el-button @click="add">Add </el-button>
      <div v-for="(item,index) in listArray" :key="index">
        <el-input v-model="item.value" placeholder="Please enter the content" class="item"></el-input>
        <i class="el-icon-close" @click="remove(index)"></i>
      </div>
  </div>
</template>
Copy the code

Let’s use vue3’s composite API, also known as composition API, to do this

<script>
import {ref} from "vue"
export default {
  setup() {
    // Initialize the array
    const listArray = ref([{value:1}, {value:2}, {value:3}])
    //add
    const add = () = >{
      listArray.value.push({value:""})}//remove
    const remove =(index) = >{
      console.log(index)
      listArray.value.splice(index,1)}console.log(listArray.value)
    return {listArray,add,remove}
  },
}

</script>
Copy the code

Compared to the options-API of VUe2,

Let’s make a summary of setup and ref

The setup function is a lifecycle hook that corresponds to the beforeCreate and Create functions in vue2 and is the entry to vue3’s Composition API. We defined by the function in vue3 vue2 of data, the methods, watch, computed properties, the setup function must have a return value, must return an object, the object contains all you need to use in the template template to properties.

ref

Takes an internal value and returns a reactive and mutable REF object. The ref object has a single property.value pointing to an internal value.

Value,steup takes two parameters: props and context. In js, this parameter represents the context, exposing the component’s property, which can be retrieved

Some people don’t like the idea of passing.value and returning multiple values to use in templates or setup, we can use reative()

Wrap data around the properties and methods we need to return and return

<script>
import {reactive} from "vue"
export default {
  setup(props,context) {
    console.log(props)
    console.log(context)
    const data = reactive({
      listArray: [{value:1}, {value:2}, {value:3}].add:() = >{
        data.listArray.push({value:' '})},remove:(index) = >{
        data.listArray.splice(index,1)}})return {data}
  },
}
</script>
Copy the code

But there is a problem with this. To use it in templates, we need to call properties and methods through data.xxx,

We naturally wondered if we could deconstruct it and assign it,

We can deconstruct the data element with toRefs(), so we get the attributes and methods directly.

<template>
  <div>
      <el-button @click="add">Add </el-button>
      <div v-for="(item,index) in listArray" :key="index">
        <el-input v-model="item.value" placeholder="Please enter the content" class="item"></el-input>
        <i class="el-icon-close" @click="remove(index)"></i>
      </div>
  </div>
</template>
<script>
import {reactive,toRefs} from "vue"
export default {
  setup(props,context) {
    // // Initializes the array
    const data = reactive({
      listArray: [{value:1}, {value:2}, {value:3}].add:() = >{
        data.listArray.push({value:' '})},remove:(index) = >{
        data.listArray.splice(index,1)}})const result = toRefs(data)
    return{... result} }, }</script>
Copy the code

The lifecycle of Vue3

As stated in the official documentation, setup() replaces the previous beforeCreate() and created lifecycle functions, and the rest of the lifecycle functions are implemented in setup().

Computed with the watch

computed

Takes a getter function and returns an immutable reactive ref object based on the return value of the getter. Alternatively, you can take an object with get and set functions to create a writable ref object.

    const count =  ref(1)
    const count2 =  ref(2)
    const plusOne = computed(() = > count.value+1)
    console.log('plusOne:'+plusOne.value)/ / 2
    //plusOne.value++ 
    const plusTwo = computed({
      get:() = >count2.value+1.set:val= >{
        count2.value = val-1}})console.log('plusTwo:'+plusTwo.value)/ / 3
    console.log(plusTwo.value++)/ / 3
Copy the code

watch

To automatically apply and reapply side effects based on reactive state, we can use the watchEffect method. It executes a function passed in immediately, tracing its dependencies responsively, and rerunking the function when its dependencies change.

const count = ref(0)
watchEffect(() = > console.log(count.value))
// -> logs 0
setTimeout(() = > {
  count.value++
  // -> logs 1

}, 100)
Copy the code

The Watch API is exactly equivalent to a component listener property. Watch needs to listen for specific data sources and perform side effects in callback functions. By default, it is also lazy, meaning that callbacks are executed only when the source being listened to changes.

  • In contrast to watchEffect, Watch allows us to:

    • Lazy execution side effects;
  • Be more specific about what state should trigger the listener to restart;
  • Access values before and after listening state changes.
// Listen for a getter
const state = reactive({ count: 0 })
watch(
  () = > state.count,
  (count, prevCount) = > {
    / *... * /})// listen on ref directly

const count = ref(0)
watch(count, (count, prevCount) = > {
  / *... * /
})
Copy the code

In contrast, vue 3 composition API life cycle functions still exist, and various ref apis have more options. However, it also brings difficulties to uniform code style. Options API does have various problems, but it also guarantees the lower limit. I think we can try @vue/composition-api for the current VUe2 project, write it down and see how it works, then consider whether to make a major upgrade.

reference

Vue 3 Official document