Differences between VUe2.0 and VUe3.0

  • Rewrote the implementation of the virtual DOM (skip static nodes and only deal with dynamic nodes).
  • Update Performance improved by 1.3 to 2 times.
  • SSR (service processing) speed increased 2-3 times.
  • You can clip useless modules and pack only what you need (as needed).
  • Not limited to a single root node in the template.
  • Better typeScript support.
  • The combined API (setup) replaces the original OptionsAPI
    • Organize code around logical dependencies to improve readability and maintainability
    • Better reuse of logical code (avoid naming conflicts when mixins are mixed in)
    • However, Options can still be used
    //Options API
    export default {
        data() {
            return{}},methods:{
        
        },
        computed: {}}// Composite API
    export default {
        setup(){}}Copy the code

How do I create a Vue3.0 project

Configure VUe3.0 based on the VUE or CLI

  • Vue/CLI scaffolding must be version 4.3.1 or later
  • Use the create project commandVue create Project name
  • Then addvue add vue-nextCreate a 3.0 project

Configure VUe3.0 based on Vite

  • There is a web development tool developed by Yu Yu Creek, a development server based on native ES Imports in the browser (imports are parsed in the browser, compiled on demand on the server side, bypassed the concept of packaging completely, and the server is available on demand), vUE file support, and hot updates. 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 apis

  • Vue3.0 reference documentation v3.cn.vuejs.org/guide/compo…

Responsive system toolset

ref

  • Accepts a parameter value and returns a reactive and mutable REF object.
    • The ref object has an attribute that points to an internal value.value
    • When ref is used in a template, it is automatically unpacked without additional writing inside the template.value(It means that when return comes out, you can use it directly with the mustache.)
    • Ref is not implemented by Proxy.

unref

  • If the argument is a ref, return its value, otherwise return the argument itself, which is val = isRef(val)? Val. value: syntax slot for val
let a = 'hello',
b = ref(2)
console.log(unref(a,b)) / / 'hello'. 2
Copy the 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 the code

toRefs

  • Convert a reactive object into a normal object, each property of which is a ref, corresponding to the reactive object property.

isRef

  • Determines whether the value is a ref object, and returns true if so, false otherwise
        let a = 0
        console.log(isRef(a)) // false
    Copy the code

isProxy

  • Checks whether an object is a proxy created by a reactive or Readonly method

isReactive

  • A reactive proxy that checks whether an object is created by Reactive.
    • If the agent created by Reactive is wrapped in another agent created by Reactive, true will also be returned

isReaonly

  • Checks whether an object is a read-only proxy created by ReadOnly.

readonly

  • Passing in an object (reactive or normal) or ref returns a read-only proxy for the original object. A read-only proxy is deep and any nested properties within the object are read-only only.

Advanced system responsive APIS

customRef

computed

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

The set callback is triggered when supNum and oppNum are changed. The set callback is triggered when a is changed (a.lovelue = a.lovelue +1).
setup() {
   let a =  computed({
   get:() = >{
       let total = state.supNum + state.oppNum
       return ((state.supNum/total)*100).toFixed(2) + The '%'
   }
   set:(val) = >{
       console.log(val,222)}})return{
       a
   }
}

Copy the code

watchEffect

  • Execute a function passed in immediately, trace its dependencies responsively, and re-run the function when its dependencies change.
    setup(props){
        watchEffect(() = >{
            console.log(props.title)// This is done immediately on the first rendering
        })
        let y = ref(0),
        z = ref(0);
        // If you need to listen for more than one value
        watchEffect(() = >{
            console.log(y.value,z.value)// We must write value, because we are listening for value, not the ref object of y})}Copy the code

watch

  • Watch is completely equivalent to watch 2.0
    • Watch needs to listen for a specific data source and execute in a callback function.
    • The default is lazy, meaning that callbacks are executed only when the source changes are being listened for. The first loading of the page is not performed, unlike watchEffect.
    // Listen for a single data
    setup(){
    watch(state,() = >{
        console.log(state.supNum)
    })
    // Listen for some data in state
    watch(() = >state.supNum,() = >{
        console.log('hello'+state.supNum)
    })
    // Listen for the reactive data created by the REF and print the changed value and the previous value
    let x = ref(0)
    setup(){
        watch(x,(x,prevX) = >{
            console.log(x,prevX)
        })
    }
    // The watch function will be triggered if any value in the array changes
    watch([x,y],([x,y],[prevx,prevy]=>{
        console.log(x,y,prevx,prevy)//prevx,prevy changes the previous value
    }))
    Copy the code

Differences between watchEffect and Watch

  • There is no need to pass in a dependency value manually.
  • A callback is executed for each initialization to get the dependency value.
  • Cannot get the original value, only the changed value.

setup

  • The setup function is a new component option that acts as an entry point to the CompositionAPI used within the component.
    • Call between initialize props and beforeCreate
    • You can accept props and context
    • This is not available in setup because it is executed before beforeCreate and this instance has not yet been created.
  • setup(props)
    • The props is based on the response data of the Proxy
  • The setup of grammar
    setup(){
        {{num}}}
        return{}}Copy the code

Build responsive data

Method one, using REF, generally dealing with simple values of the response formula

  • Again, the principle is based on defineProperty listening for value values
<template>
  <div>
    <h3>{{ title }}</h3>
    <div>
      <p>Support number :{{supNum}}</p>
      <p>Objectors :{{oppNum}}</p>
      <p>Support:</p>
      <button @click="change(0)">support</button>
      <button @click="change(1)">against</button>
    </div>
  </div>
</template>

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

// 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
    }
{{state. SupNum}}}
}
Copy the code

Second, reactive

  • Based on Proxy, the data is deeply monitored to build responsiveness
    • A responsive proxy that takes a normal object and returns that normal object
    • Reactive transformations are deep, affecting all nested properties inside the object
setup() {
    let state = reactive({
       supNum: 0OppNum;0
    })
    function change(x){
        x == 0? state.supNum++ : state.oppNum++
        DefineProperty is better than Object.defineProperty in that values can be arbitrarily changed for and data or uninitialized Object members, and have responsive data.
    }
    return{
        ...toRefs(state),
        change
    }
    {{supNum}}}
}
Copy the 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 the code

Life cycle function

  • beforeCreate= > using the setup
  • create= > using the setup
  • BeforeMount =>onBeforeMount Before the first mounting
  • Mounted =>onMounted After the first mount
  • BeforeUpdate =>onBeforeUpdate component before updating
  • Updated =>onUpdated After the component is updated
  • BeforeDestroy =>onBeforeUnmount Before the component is destroyed
  • Destoryed =>onUnmounted After the component is destroyed
  • errorCaptured=>onErrorCaptured