Upgrade Vue 3.0 project

Currently, creating Vue 3.0 projects requires plug-in upgrades.

Vue-cli does not support creating Vue3.0 projects directly yet. First we go to the project directory and enter the following command:

cd vue-next-test
vue add vue-next
Copy the code

setup

The setup() function is a new property in VUe3 specifically for components. It provides a unified entry point for using vue3’s new Composition API features.

The setup function is executed after beforeCreate and before Created

Setup is a new component option that is also an entry point to other apis. That is, all of your operations will be defined and performed inside the setup function, and Vue3.0 will replace the vue2. x class with a function called new Vue(). 3. When is it invoked? Setup is called after props is initialized when a component instance is created, replacing careted and beforeCreate of Vue2. X. Setup returns an object whose properties are directly exposed to the template rendering context. In Ve2. X, the attributes you define are unconditionally exposed to the template rendering context inside Vue.Copy the code

Receive the prop

 props: {
    p1: String,
  },
  setup(props, context) {
    console.log(props.p1);
    
  },
Copy the code

context

The second parameter to the setup function is a context object containing some useful properties that need to be accessed through this in vue 2.x. In vue 3.x, they are accessed as follows:

const MyComponent = {
  setup(props, context) {
    context.attrs
    context.slots
    context.parent
    context.root
    context.emit
    context.refs  
  }
}
Copy the code

computed

Computed values behave the same as computed properties: they are recalculated only when dependencies change. Type useCallback useMemo of an act.

Computed () returns a wrapper object, which can be returned in setup() just like a normal wrapper object and expanded automatically in the render context.

Usage:

setup() { const num = ref(0); Const get_num = computed(() => num. Value + "computed attribute "); return { num, get_num, }; },Copy the code

Use 2:

// Create a const count = ref(1) // Create a computed property const plusOne = computed({get: () => count. Value + 1, // set: Val => {count. Value = val - 1}}) The count value is updated console.log(count.value) // to print 8Copy the code

Compute properties and data listening

import { ref, computed, watch, watchEffect } from "vue"; export default { setup() { const count = ref(0); const doubleCount = computed(() => { return count.value * 5; }); watch( () => count.value, (val, oldVal) => { console.log(`count is ${val}`); }, {// Whether to listen deep: true, // whether to execute the first immediate: true}); function add() { count.value++; } return { count, add, doubleCount }; }};Copy the code

Computed properties computed is a method that includes a callback function that gets its value automatically when we access the results returned by computed properties.

The listener watch is also a method, which contains three parameters, the first two parameters are function, the third parameter is whether to deep listen, etc.

The first argument is the value of the listener. Count. Value indicates that when count. Value changes, the listener’s callback function is triggered.

If there are more than two listener properties,

Watch ([() => count.value, () => name.value], // Accept two arguments, the first is the new value in the array, The second is the old value is also in the array ([count, name], [oldCount, oldName]) => {console.log(count, name); console.log(oldCount, oldName); if (count ! = oldCount) {console.log("count sounds changed "); } if (name ! = oldName) {console.log("name voice change "); }});Copy the code

To get the routing

Const vue = getCurrentInstance(); Const {CTX} = getCurrentInstance(); Console. log(CTX.$router); $router. Push ("/about"); }Copy the code

The life cycle

2. Mapping between X lifecycle options and Composition API

  • BeforeCreate -> Use setup()
  • Created -> Setup ()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

Vuex is simple to use

import Vuex from 'vuex'

export default Vuex.createStore({
  state: {
    num: 1,
  },
  mutations: {
    add(state, value) {
      console.log(value)
      state.num++
    },
    decrement(state, value) {
      console.log(value)
      state.num--
    }
  },
  actions: {
  },
  modules: {
  }
});
Copy the code

Mount to Vue

import router from './router'
import store from './store'

createApp(App).use(router).use(store).mount('#app')
Copy the code

Component use:

<template> <div class="home"> <h1>VUEX uses </h1> <div> original values: {{num}} < / div > < div > < button @ click = "add" > add < / button > < button @ click = "decrement" > reduce < / button > < / div > < / div > < / template > <script> import { computed } from "vue"; import { useStore } from "vuex"; export default { setup() { const store = useStore(); const num = computed(() => store.state.num); Function add() {store.mit ("add", "add"); function add() {store.mit ("add", "add"); Store.dispatch ('action', payload)} function decrement() {store.com MIT ("decrement", "less "); } return { num, add, decrement }; }}; </script>Copy the code