Fully embrace vue3 0

Posted by daniminas on Thu, 10 Feb 2022 16:02:04 +0100

vue2.0 and vue3 Difference between 0

  • Rewrite the implementation of virtual DOM (skip static nodes and only deal with dynamic nodes).
  • update performance is improved by 1.3 ~ 2 times.
  • SSR (service processing) speed is increased by 2 ~ 3 times.
  • You can clip useless modules and package only what you need (package on demand).
  • Not limited to a single root node in the template.
  • Better typeScript support.
  • The composite API (setup) replaces the original options API
    • Organize code according to logical relevance to improve readability and maintainability
    • Better reuse of logical code (avoid naming conflicts when mixins are mixed)
    • But you can still use Options
    //Options API
    export default {
        data() {
            return{
            
            }
        },
        methods:{
        
        },
        computed:{
        
        }
    }
    
    //Combined API
    export default {
        setup(){
        
        }
    }
    Copy code

How to create vue3 0 project

Configure vue3 based on vue/cli 0

  • vue/cli scaffold must be above version 4.3.1
  • Use the create project command vue create project name
  • Finally, add Vue add Vue next to create a 3.0 project

Configure vue3 based on vite 0

  • There is a web development tool developed by you Yuxi and a development server based on the browser's native ES imports (use the browser to parse imports, compile and return on demand on the server side, completely skip the concept of packaging, and the server can be used as needed). At the same time, it not only has the support of vue files, but also solves the hot update, and the speed of hot update will not slow down with the increase of modules.
  • NPM I vite app project name
  • cd project name
  • npm i
  • npm run dev

Master setup and responsive system API

Responsive system Toolset

ref

  • Receives a parameter value and returns a responsive and changeable ref object.
    • The ref object has an attribute that points to an internal value value
    • When ref is used in the template, it will be automatically unrolled without additional writing inside the template value (meaning return can be used directly with a moustache)
    • ref is not implemented by Proxy.

unref

  • If it is a parameter, ref = value (otherwise, it returns a value of the parameter itself)? Val.value: the syntax slot of val
let a = 'Hello',
b = ref(2)
console.log(unref(a,b)) //'hello', 2
 Copy code

toRef

  • Convert parameters to ref objects, for example
    let a = 0;
    console.log(toRef(a)) //ObjectRefImpl {_object: 0, _key: undefined, __v_isRef: true}
    Copy code

toRefs

  • Turn the responsive object into an ordinary object. Each property of the ordinary object is a ref, which corresponds to the property of the responsive object one by one.

isRef

  • Judge whether the value is a ref object. If yes, it returns true; otherwise, it is false
        let a = 0
        console.log(isRef(a)) // false
     Copy code

isProxy

  • Check whether an object is a proxy created by the reactive or readonly method

isReactive

  • Check whether an object is a reactive proxy created by reactive.
    • If this agent is created by reactive, but is wrapped by another agent created by reactive, true will also be returned

isReaonly

  • Check whether an object is a read-only proxy created by readonly.

readonly

  • Pass in an object (reactive or normal) or ref, and return a read-only proxy of the original object. A read-only proxy is deep, and any nested attributes inside the object are only read-only.

Advanced system responsive API

customRef

computed

  • Pass in a getter function and return a ref object that cannot be modified manually by default.
// The first writing method: the value cannot be modified manually
setup() {
   let a =  computed(()=>{
       let total = state.supNum + state.oppNum
       return ((state.supNum/total)*100).toFixed(2) + '%'
   })
   return{
       a
   }
}

//The second writing method: you can use set to modify. When the values supNum and oppNum that a depends on change, the get callback function will be triggered. If you modify the value of a, the set callback function will be triggered (a.vlue = a.vlue+1 will be triggered)
setup() {
   let a =  computed({
   get:()=>{
       let total = state.supNum + state.oppNum
       return ((state.supNum/total)*100).toFixed(2) + '%'
   }
   set:(val)=>{
       console.log(val,222)
   }   
   })
   return{
       a
   }
}

Copy code

watchEffect

  • Execute an incoming function immediately, track its dependencies responsively, and rerun the function when its dependencies change.
    setup(props){
        watchEffect(()=>{
            console.log(props.title)//The first rendering is executed immediately
        })
        let y = ref(0),
        z = ref(0);
        //If you need to listen for multiple values
        watchEffect(()=>{
            console.log(y.value,z.value)//The value value must be written, because we are listening for the value value, not the ref object of y
        })
    }
    Copy code

watch

  • Watch is completely equivalent to 2.0 watch
    • watch needs to listen to a specific data source and execute it in the callback function.
    • The default is lazy execution, that is, the callback is executed only when the listening source changes. The first page loading is not executed, which is different from watchEffect.
    //Listen for individual data
    setup(){
    watch(state,()=>{
        console.log(state.supNum)
    })
    //Listen for some data under state
    watch(()=>state.supNum,()=>{
        console.log('Hello'+state.supNum)
    })
    //Listen to the responsive data created by ref and output the changed value and the previous value
    let x = ref(0)
    setup(){
        watch(x,(x,prevX)=>{
            console.log(x,prevX)
        })
    }
    //Listen to multiple data and use the array to pass parameters. Any value change in the array will trigger the watch function
    watch([x,y],([x,y],[prevx,prevy]=>{
        console.log(x,y,prevx,prevy)//prevx,prevy change the previous value
    }))
    Copy code

The difference between watchEffect and watch

  • There is no need to manually pass in dependency values.
  • The callback function will be executed once every initialization to get the dependency value.
  • The original value cannot be obtained, only the changed value can be obtained.

setup

  • The setup function is a new component option that serves as an entry point to the composition API used within the component.
    • Initialize the call between props and beforeCreate
    • Can receive props and context
    • This is not available in setup because it was executed before beforeCreate, and this instance has not been created at this time.
  • setup(props)
    • props is the response data based on Proxy proxy
  • setup syntax
    setup(){
        //return values can be used directly in html, {{num}}
        return{
        
        }
    }
    Copy code

Building responsive data

Method 1: using ref, generally deal with the response formula of simple value

  • The principle is still based on the value value of defineProperty
<template>
  <div>
    <h3>{{ title }}</h3>
    <div>
      <p>Number of support:{{ supNum }}</p>
      <p>Number of opponents:{{ oppNum }}</p>
      <p>rate of support:</p>
      <button @click="change(0)">support</button>
      <button @click="change(1)">opposition</button>
    </div>
  </div>
</template>

// The first is to use ref directly, which is troublesome
setup() {
    let supNum = ref(0),
    oppNum = ref(0);
    functiom change(x){
        x == 0? supNum.value++:oppNum.value++
    }
    return{
        supNum,
        oppNum,
        change,
    }
}

// The second type of ref is to create a ref object
setup(){
    let state = ref({
        supNum:0
        oppNum:0
    })
    function change(x){
        x == 0? state.value.supNum++ : state.value.oppNum++
    }
    return{
        state
    }
//When using html, {{state.supNum}}
}
Copy code

Method 2: use reactive

  • Deep monitoring of data based on Proxy to build response
    • Receive a normal object and then return the responsive proxy of the normal object
    • Responsive transformations are deep-seated and affect all nested properties within an object
setup() {
    let state = reactive({
       supNum: 0,
       oppNum; 0
    })
    function change(x){
        x == 0? state.supNum++ : state.oppNum++
        // Than object Defineproperty is useful because it can change the value of object members that are related to data or uninitialized, and has responsive data.
    }
    return{
        ...toRefs(state),
        change
    }
    //When using html, {{supNum}}
}
Copy code

Template refs

<template>
  <div>
    <div ref="root">Hello</div>
  </div>
</template>
export default {
setup(){
    let root = ref();
    onMounted(()={
        console.log(root.value) //The return value is the div element
    })
    return{
        root
    }
}
}
Copy code

Life cycle function

  • Beforecreate = > use setup
  • Create = > use setup
  • Beforemount = > onbeforemount before the first mount
  • Mounted = > onmounted after the first mount
  • BeforeUpdate = > onbeforeupdate before component update
  • Updated = > onupdated after component update
  • Beforedestroy = > onbeforeunmount before component destruction
  • Destroyed = > onunmounted after the component is destroyed
  • errorCaptured=>onErrorCaptured