Home>

Foreword

I watched Youda ’s live broadcast on the evening of the 21st of this month,I feel vue3.0 is getting closer and closer to us,It is expected to be officially released in the middle of the year,The change in 3.0 is indeed great,Performance has improved a lot,Many things are also relying on react. In order to quickly switch to the vue3.0 camp, it is necessary to become familiar with the new features from now on.

If i want to use 3.0 content in v2.x, you can use the following methods

npm install "@ vue/composition-api"

Introduced in main.js

import vuecompositionapi from "@ vue/composition-api";
vue.use (vuecompositionapi);

Two-way data binding

The two-way data binding in v2.x is achieved through the object's defineproperty method,The intercept operation is performed through the get and set methods in the attribute.But it cannot monitor the changes of the array,In addition to using the following methods:push (), pop (), shift (), unshift (), splice (), sort (), reverse (), if you directly use index to set an item in the array, it cannot be changed of.

v3.x uses proxy and reflect to achieve two-way binding,It can monitor changes in objects from more aspects,In addition to set and get, also provides apply, setprototypeof, getprototypeof, deleteprototype, isextensible, preventextensions, getownpropertydescriptor, defineproperty, has, ownkeys, construct method monitoring.

I will explain the actual application of proxy in the later period.This issue focuses on the practice of vu3.0

Example of direct catty

<template>
  <div>
    <h3>Data binding</h3>
    <div>
      <[email protected]="clicksingleval">
        One-way binding {{singleval}}
      </el-button>
      <[email protected]="clickdoubleval">
        Two-way binding {{doubleval}}
      </el-button>
      <[email protected]="clickstateval">
        State binding {{stateval}}
      </el-button>
    </div>
  </div>
</template>
​
​
<script>
import {ref, reactive, torefs} from "@ vue/composition-api"
export default {
  setup () {
    let singleval=1
    const doubleval=ref (1)
    const state=reactive ({
      stateval:1
    })
    const methods={
      clicksingleval () {
        singleval ++
        console.log (singleval);
      },      clickdoubleval () {
        doubleval.value ++
      },      clickstateval () {
        state.stateval ++
      },    }
    return {
      singleval,      doubleval,      ... torefs (state),      ... methods
    }
  }
}
</script>
<style>
</style>

If you are reading this for the first time, it may be a bit strange,This is how it is written in vue3.x.In v2.x, data, methods, computed, watch, etc. are all written in a function called setup in v3.x.Inside, we can define variables, functions, etc. arbitrarily, and finally return through return, the returned content can be used in the template.

More detailed classification of the bound data in v3.x,Can be divided into the following three types:

One-way binding:var singleval=1, the data will change,But the view will not update Single two-way binding:const doubleval=ref (1), use doubleval.value to change Two-way binding:need to use reactive, use state.stateval to change the value

Let's explain one by one:

One-way binding,You can know by listening to the name that it does not have two-way binding features or functionsIt will only be bound once when the view is initialized,Even if this variable is changed later,The view will not be updated.You can see from the console that the value of singleval has indeed changed,But the interface always shows 1. The method of variable declaration is the same as we usually declare a variable,Such as:let singleval=1, and finally return in return. Single two-way binding,Only one two-way bound variable can be declared at a time,Create a wrapper object through the ref function,Make it contain a responsive attribute value. For example, const doubleval=ref (1) above. If i want to change its value,What needs to be changed is the value on its attribute value, like this doubleval.value ++. Two-way binding,Create a responsive object through reactive,The object created in this way is not a wrapper object,Therefore no need to use.value to get the value, it is equivalent to vue.observable of vue 2.x.

const state=reactive ({
  stateval:1
})
return {
 ... state
}

Directly deconstruct the reactive content and return,Will cause responsive loss,You need to use torefs to convert reactive objects to ordinary objects,In this way, each attribute on the result object points to the ref reference object of the corresponding attribute in the original object,It ensures that the responsiveness will not be lost when using object destructuring or expansion operators.

For event methods,Just like declaring a variable,Declare in setup, just return in return.

Calculated attributes

Introduce the computed method and return the calculated value,Then use the above example,Use total to calculate the sum of the above three numbers.

import {computed, ref, reactive, torefs} from "@ vue/composition-api"
export default {
  setup () {
    ...
    const total=computed (() =>{
      return singleval + doubleval.value + state.stateval
    })
    ...
    return {
      ...,      total
    }
  }
}

We can also see from the demo effect,One-way bound data changes will not trigger the calculated attribute method.

Data monitoring

It is also written in the setup, which is relatively simple,Nothing to explain

import {computed, ref, reactive, torefs, watch} from "@ vue/composition-api"
...
watch (() =>state.stateval, (newval, oldval) =>{
  console.log (newval, oldval);
})
...

Life cycle

The two cycles of beforecreate and created were cancelled in vue3.0,Because the setup will be executed before this cycle,So you can do what you need in setup.All other life cycles begin with on.

import {
  onbeforemount,  onmounted,  onbeforeunmount,  onbeforeupdate,  ondeactivated,  onunmounted,  onupdated
} from "@ vue/composition-api"
export default {
  setup () {
    onbeforemount (() =>{
      console.log ("onbeforemount");
    })
    onmounted (() =>{
      console.log ("onmounted");
    })
    onbeforeunmount (() =>{
      console.log ("onbeforeunmount");
    })
    onbeforeupdate (() =>{
      console.log ("onbeforeupdate");
    })
    ondeactivated (() =>{
      console.log ("ondeactivated");
    })
    onunmounted (() =>{
      console.log ("onunmounted");
    })
    onupdated (() =>{
      console.log ("onupdated");
    })
  }
}

mixin

In vue3.0, functional APIs are used to replace the original mixin. Mixin is easy to cause naming coincidence and cover page attributes introduced by mixin.

It exists in the form of an api in vue3.0,When you need it,Introduce it.Look directly at the example

mixin.vue

<template>
  <div>
    <h3>mixins</h3>
    <div>
      <el-input v-model="searchvalue" type="text"@change="onsearch" />
      <div>
        <ul>
          <li v-for="name in names":key="name.id" v-show="name.show">
            {{name.value}}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
​
<script>
import searchname from "./searchname.js"
export default {
  setup () {
    let list=[
      {id:1, value:"vue", show:true},      {id:2, value:"react", show:true},      {id:3, value:"angular", show:true},      {id:4, value:"elementui", show:true},      {id:5, value:"ant", show:true},      {id:6, value:"javascript", show:true},      {id:7, value:"css", show:true},    ]
    var {onsearch, names, searchvalue}=searchname (list)
    return {
      onsearch,      names,      searchvalue
    }
  }
}
</script>
<style>
</style>

searchname.js

import {reactive, torefs} from "@ vue/composition-api"
​
export default function searchname (names) {
  const state=reactive ({
    names:names,    searchvalue:""
  })
  const onsearch=() =>{
    state.names.foreach (name =>{
      name.show=name.value.includes (state.searchvalue)
    })
  }
  return {
    ... torefs (state),    onsearch
  }
}

Above we separate the search function into a js file. Some properties and methods are defined in searchname.js,The attributes here are also responsive,Finally return these contents.In the component,First introduce this js file, call the searchname method, and pass in the required parameters.The two responsive data of searchvalue and names in this component are not all of their own.It comes from searchname.js, as you can see from the demo below,They are indeed responsive.

eventbus

Setup receives two parameters props:equivalent to props in v2.x:{}, used to receive the parameters passed by the parent component

ctx:context.In 2.x, this refers to the global vue instance, you can use this.router,this.router, this.router, this.commit, this.emitetc.SquareMethodEnterOKRoadBy'sJumpSwitch toetc.FuckFor.AndOn3.0MediumNoCanStraightTakeVisitAskTothis,such asFruitYouTasteTryLoseOutthis,YouBack toSeeToIt'sValueYesundefined.ButMayWiththrougheverctx.root.emit and other methods for routing and other operations.In 3.0, this cannot be accessed directly. If you try to output this, you will see that its value is undefined. However, routing jumps and other operations can be performed through methods such as ctx.root.emit.In 3.0, this cannot be accessed directly. If you try to output this, you will see that its value is undefined. But you can hang the content on $root through ctx.root.root. $Emit so that it can be accessed from anywhere.

setup (props, ctx) {
 ...
 const total=computed (() =>{
   let total=singleval + doubleval.value + state.stateval
   ctx.root. $root. $emit ("handleclick", {number:total})
   return total
 })
 ...
}
...
ctx.root. $root. $on ("handleclick", (val) =>{
  console.log ("I was triggered by ctx.root. $root. $on, the received value is:" + val.number);
  state.othertotal=val.number
})
...

Finally, the composition-api github is attached:https://github.com/vuejs/composition-api

Related articles

  • Previous Unity Shader achieves dynamic fog effect
  • Next Unity shader to achieve glass refraction effect