The documentation for Vue 3 is available in Chinese and is detailed, as well as a guide for migrating Vue 2 to Vue 3. So here are just some of the new features I used and some of my understandings.

Vue 3 data response

The underlying implementation of Vue 2’s data responsiveness is Object.defineProperty(), which intercepts seven methods of arrays. The problem with this approach is that there is no way to detect the addition or deletion of attributes to the object. Changes based on array indexes are also not detected.

Vue 3’s data responsiveness is implemented as an ES6-based Proxy, the same as Mobx 6. Solve the problems mentioned above

  • Proxy can be used to listen directly on objects rather than attributes, so the addition and deletion of attributes of objects can also be monitored
  • The Proxy can listen for changes to the array directly. Therefore, the content or length of the array directly modified subscript can also be listened on
const hero = {
    name: "Zhaoyun".hp: 100.sp: 100.equipment: ['the horse'.'long']}const handler1 = {
    get(target, name, receiver) {
        return Reflect.get(target, name, receiver)
    },
    set(target, key, value, receiver) {
        console.log(`hero's ${key} change to ${value}`)
        return Reflect.set(target, key, value, receiver)
    }
}
const handler2 = {
    set(target, key, value, receiver) {
        console.log(`equipment's ${key} change to ${value}`)
        return Reflect.set(target, key, value, receiver)
    }
}
const heroProxy = new Proxy(hero, handler1)
const equipmentProxy = new Proxy(heroProxy.equipment, handler2)
heroProxy.equipment = equipmentProxy
// Hero's equipment change to a horse
heroProxy.name = "Zhang fei"
// Hero's name change to Zhang Fei
heroProxy.equipment[2] = "Armor"
// Equipment's 2 change to armor
heroProxy.level = 100
//hero's level change to 100
Copy the code

Composition API

The main purpose is to make it easier to split and reuse code, and Vue 2 needs to use mixins if it wants to reuse code. There are official examples, but I feel the Composition API is a bit like the React custom Hooks.

setup

There is no this in setup, only props and context

import {toRefs} from 'vue'
setup(props){
    // const {title} = props 
    // ES6 deconstruction will eliminate the responsiveness of prop, if the deconstruction is to be written as follows
    const {title} = toRefs(props)
    console.log(title.value)
}
Copy the code

Context has the following properties

  • props
  • attrs
  • slots
  • emit

Lifecycle hook

The Setup lifecycle hook is basically an on on top of the optional API

export default {
    setup(){
    onMounted(() = >{... }}})Copy the code

Ref and reactive

Both REF and Reactive are used to add reactive state to data, but Reactive only accepts parameters of object types. Reactive is used for objects and ref is used for base types. JS uses a.value for the ref object; Template does not.

const count = ref(0)
console.log(count.value) / / 0
Copy the code

Provide / Inject

Similar to Provide and Inject in Vue 2, Provide and Inject are used for communication between components. You can make the data provided by provide read-only component of Inject.

<template>
  <MyMarker />
</template>
<script>
import { provide, reactive, readonly, ref } from 'vue'
import MyMarker from './MyMarker.vue

export default {
  components: {
    MyMarker
  },
  setup() {
    const location = ref('North Pole')
    const geolocation = reactive({
      longitude: 90,
      latitude: 135
    })
    const updateLocation = () => {
      location.value = 'South Pole'
    }
    provide('location', readonly(location))
    provide('geolocation', readonly(geolocation))
    provide('updateLocation', updateLocation)
  }
}
</script>
Copy the code

Teleport

We can move elements to where we want them

<teleport to="body">
	<div>.</div>
</teleport>
Copy the code

Changes to v-Model usage

The V-model in Vue 2 is equivalent to binding value prop and input events:

<ChildComponent v-model="pageTitle">
<! -- is short for: -->
<ChildComponent :value="pageTitle" @input="pageTitle = $event"/>    
Copy the code

The V-Model in Vue 3 is more like.sync

<! -- Vue2 -->
<ChildComponent :title.sync="pageTitle"/>
<! -- Vue3 -->
<ChildComponent v-model:title="pageTitle"/>
Copy the code

Component events need to be declared in the emits option

Components need to declare triggered events in emits

export default {
    emits: ['accept'.'cancel']}Copy the code

Otherwise the console will have a warning

watchEffect

Much like MobX’s Autorun, it executes the incoming function immediately and traces its dependencies in a responsive manner, reexecuting it depending on the change

const count = ref(0)
watchEffect(() = > console.log(count.value))
// -> logs 0
setTimeout(() = > {
  count.value++
  // -> logs 1
}, 100)
Copy the code

The difference with Watch

  • Watch can access values before and after the listening state changes
  • Watch only performs callbacks when the source it is listening to changes
  • Can you be more specific when the callback function is executed

V – for the Ref

Ref can bind a function to determine which Dom element to bind

<div class="color-tabs-nav-item" v-for="(t,index) in titles" :ref="el => { if (index === selectedIndex) this.selectedItem = el }"
   :key="index">{{ t }}
 </div>
Copy the code

reference

  1. Practice ES6 Proxy & Reflect
  2. Vue 3 documentation – In – depth responsive principles
  3. ECMAScript introduction to 6
  4. Vue 3.0 Study Notes