1. Comparison of responsive principles between VUe2.0 and VUe3.0

1. Responsivity principle of VUe2.0

Reactive data is implemented in Vue2.0 using the Object. DefineProperty method in ES5

Disadvantages:

  1. Unable to listen to dynamic additions and deletions of object properties
  2. Cannot listen for array subscript and length property changes

Solution:

  1. Vue2.0 provides vue.set methods for dynamically adding attributes to objects
  2. Vue2.0 provides the vue.delete method to dynamically delete an object’s attributes
  3. Overrides array methods in VUE to detect array changes

1.1 Object. DefineProperty

const data = { name: 'ly', age: 18 } for (let k in data) { let temp = data[k] Object.defineProperty(data, k, Return temp}, set(value) {console.log(' I hijacked the setting of ${k}, Value ${value} ') temp = value}})} in the console access 1.data. name I hijked name get "ly" 2. Modify: data.name = 'ls' I hijacked the name setting, value ls" ls"Copy the code
Disadvantages:

Unable to monitor changes and deletions of new properties

  1. When modifying data to modify a property that does not exist:
Gender = "male" is not hijacking data at this timeCopy the code
  1. When deleting an attribute from data:
Delete data.name true although deleted, there is no hijackingCopy the code

1.2. Responsive data in VUe2

Vue requires the $set method to dynamically add a reactive attribute

Vue requires the $delete method to dynamically delete an object’s attributes

/ / price in data is not defined in the < p > {{car. Brand}}, {{car. Color}} - {{car. Price}} < / p > data: {car: {brand: 'Mercedes', color: Mercedes ----blue----- vm. Car. Brand = 'BMW' BMW ----blue----- BMW vm.car. Price = '100' BMW ----blue----- Vm.$set(vm. Car, 'price', 100) BMW ----blue-----100 2. In vue, you need to use the $delete method to dynamically delete object attributes. $delete(vm.car, 'brand') modified page display: ----blue-----Copy the code

2. Responsivity principle of VUe3.0

The proxy syntax in ES6 is used for reactive data in VUe3.0

advantages

  1. Dynamic addition and removal of proxy object properties can be detected
  2. Changes to the array’s subscript and length properties can be detected

disadvantages

  1. The PROXY syntax of ES6 does not support IE11 in older browsers
  2. There will be a special version of VUe3.0 for IE11 support

2.1. Proxy syntax in ES6

const data = { name: 'ly', age: 18} const proxyData = new Proxy(data, {get(target, name) {console.log(' detected ${name} fetch ') return target[name]}, Set (target, name, value) {console.log(' detected setting ${name} ', ${value}) target[name] = value}, deleteProperty(target, Key) {console.log(' detected delete ${key} ') return delete target[key]}}) "Ly" proxydata. name = 'ww' Set of name detected with value ww "ww" delete proxyData.name Detected with value deleted name trueCopy the code

2.2. Responsive data in VUe3

Add and delete directly without setting, set, set, delete.

/ / price in data is not defined in the < p > {{car. Brand}}, {{car. Color}} - {{car. Price}} < / p > data: {car: {brand: 'Mercedes', color: Mercedes ----blue----- vm.car. Price = 100 Mercedes ----blue-----100 delete vm.car. Brand ----blue-----100Copy the code

2. Initialize the project

To upgrade a 2.0 project to a 3.0 project, run the following command: vue add vue-next

2.1 Using vue-CLI to Create vue3.0 Projects

  1. Install the vue – cli3
npm install -g @vue/cli
Copy the code
  1. Create a project
vue create my-project
Copy the code
  1. Install composition-API in your project to experience the new vuE3 features
npm install @vue/composition-api --save
Copy the code
  1. Before using any of the capabilities provided by @vue/ compositon-API, it must be installed via vue.use ()
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)
Copy the code

2.2 Creating a VUe3.0 Project using Vite

  1. Vite is a Web development build tool powered by native ESM, developed based on browser native ESimports in development environment and packaged based on Rollup in production environment.

  2. Vite currently supports only vue3.X, not vuE2.X project.

  3. Vite basic use

NPM init vite-app Project name CD Project name NPM install NPM run devCopy the code
  1. Read More: With Vite, do YOU still need WebPack?

3. Use of Composition API

3.1 Composition API compared to options API

The options API:

  1. The advantage is that it is easy to learn and use, and the code has a clear place to write.
  2. The disadvantage is that similar logic is not easy to reuse, especially in large projects.
  3. The same logic can be extracted through mixins, but it is prone to naming conflicts and unclear origins.

Composition API:

  1. Composition apis organize code by logical functions, putting all the apis together for one function.
  2. Even if the project is large and has many features, you can quickly locate all the apis for that feature.
  3. The Composition API provides code readability and maintainability.

Composition API is recommended in Vue3.0, and options API is retained.

The options API:

Composition API:

3.2 Use of Setup

  1. The setup function is a new component option that serves as a starting point for the component Composition API
  2. From a lifecycle hook perspective, setup is executed before the beforeCreate hook function
  3. Setup cannot use this; this points to undefined

3.3 Use of Reactive

Reactive functions take a common object and return a reactive proxy for that object.

  1. No data is returned from setup, and an error is reported.
<p>{{car. Brand}}</p> setup() {// Define data const car = {brand: 'BMW ', price: 1000}}Copy the code

  1. Therefore, setup needs to return values in order for the values returned from setup to be used in the template. But the data is not responsive.
<p>{{car. Brand}}</p> setup() {// Define data const car = {brand: 'BMW ', price: 1000} return {car}}Copy the code
  1. Reactive passes in a normal object and returns a proxy object.
Import {reactive} from 'vue' setup() {const car = reactive({brand: 'BMW ', price: 1000}) return {car}}Copy the code

3.4 Use of ref

  1. The ref function takes a value of a simple type and returns a mutable ref object. The returned object has a unique attribute value.

  2. In the setup function, values are accessed through the value property of the REF object.

  3. In the template, the ref attribute is automatically unpacked, and no additional.value is required.

  4. If a REF accepts an object, reactive is called automatically.

// If ref is used in the template, it will be unwrapped automatically and value will be called automatically. <div> import {ref} from 'vue' setup() {// define data // the ref function accepts a simple type, Let money = ref(100) // This reactive object has only one attribute value // After receiving a simple data type through ref, the new value is actually an object. The.value access is required if you want to use it below. Value money. Value++ return {money}}Copy the code

3.5 Use of toRefs

  1. To convert a response time object to a normal object, each attribute of the object is a ref

  2. Reactive is given to objects, but if the object is deconstructed or expanded, the data loses that ability

  3. Using toRefs ensures that every property that the object expands is reactive

Setup () {const money = ref(100) const car = reactive({brand: 'BMW ', price: 100000 }) const XXXX return {money, car,..... }} There's a problem: there's more and more dataCopy the code
Setup () {const state = reactive({money: 100, car: {brand: 'BMW ', price: 100000}}) return {... There is a problem with this: when the object is deconstructed or expanded, the data loses its responsiveness. In this case, money loses its responsiveness. Car is not lost because it is still an object. If you continue to structure CAR, then car also loses responsivenessCopy the code
Import {toRefs} from 'vue' setup() {const state = reactive({money: 100, car: {brand: Price: 100000}}) return {... ToRefs (state)}} Uses toRefs to pass in objects and then deconstruct them so that the data is reactiveCopy the code

3.6 Using the ReadOnly Function

  1. Passing in an object (reactive or plain) or ref returns a read-only proxy of the original object
  2. A read-only agent is “deep” and read-only to any nested properties within it
  3. Can prevent objects from being modified
Template: <div> My money: {{money}} < / div > < div > {{car. Brand}}, {{car. Price}} < / div > < button @ click = "money++" > button < / button > < button @ click = "car. Price </button> setup() {const money = ref(100) const car = readonly({brand: 'BMW ', price: Return {money: readonly(money) car}} You cannot change the value of priceCopy the code

3.7 Use of computed attributes

1. An overview of the

  1. A computed function is used to create a computed property
  2. If a getter is passed in, it returns a calculated property that is not allowed to be modified
  3. If an object is passed in with getter and setter functions, a computed property is returned that allows modification

2. Implement the method of calculating attributes

  1. The first way to implement evaluating attributes is:

Passing a function getter returns a calculated property that is not allowed to be modified

setup() { const age = ref(18) const nextAge = computed(() => { return parseInt(age.value) + 1 }) return { age, NextAge}} nextAge is not allowed to be modifiedCopy the code
  1. The second way to evaluate attributes (which can be retrieved and modified) is:

Passing in an object, including get and set, creates a calculated property that can be modified

Setup () {const nextAge2 = computed({get() {reutrn parseInt(age.value) + 2} set(value) {// value is the modified value age.value = value -2 } }) return { nextAge2 } }Copy the code

3.8 Watch Uses the listening attribute

1. An overview of the

  1. The watch function takes three arguments.

    1. Parameter 1: data source, which can be a ref or getter function
    2. Parameter 2: callback function
    3. Parameter 3: additional options, {deep: true, immediate: true}
  2. Watch can listen on a ref or a getter function with a return value

  3. Watch can listen to a single data source or multiple data sources

  4. The watch function returns a value to stop listening

2. Use of listening properties

  1. Want to listen for the wrong presentation of Money
Template: <div> My money: {{money}} < / div > < div > {{car. Brand}}, {{car. Price}} < / div > < button @ click = "money++" > button < / button > < button @ click = "car. Price </button> setup() {const state = reactive({money: 100, car: {brand: 'BMW ', price: 100000}}) watch(state.money, (value, oldValue) => {console.log('money changed ', value, oldValue)}) return {... ToRefs (state)}} writing this will warn ⚠️ that it is possible to listen on a ref or a getter function with a return valueCopy the code

Correct :() => state.money

Watch (() => state.money, (value, oldValue) => {console.log('money changed ', value, oldValue)})Copy the code
  1. If money is placed outside, use ref. Watch the writing
Setup () {const money = ref(100) watch(money, (value, oldValue) => {console.log('money changed ', value, oldValue) }) return { money } }Copy the code
  1. Listen for complex data types

{deep: true}

Setup () {const state = reactive({car: {brand: 'BMW ', price: 100000}}) watch(() => state-car, (value, oldValue) => {console.log(' car changed ', value, oldValue)}, {deep: true, immediate: true}) return { ... toRefs(state) } }Copy the code
  1. Listen for multiple values
Setup () {const state = reactive({money: 100, car: {brand: 'BMW ', price: 100000 } }) watch([() => state.money, () => state.car], ([newMoney,newCar], [oldMoney,oldCar]) => {console.log(' data changed ', newMoney, newCar, oldMoney,oldCar)}) return {... toRefs(state) } }Copy the code
  1. Listen directly to state
Setup () {const state = reactive({money: 100, car: {brand: 'BMW ', price: 100000}}) watch(state, (value) => {console.log(' data changed ', value)},{deep: true, immediate: true}) return {... toRefs(state) } }Copy the code

3.9 Lifecycle hook functions

  1. Vue3 provides lifecycle hook function registration functions that can only be used synchronously during setup ()
  2. Vue3 lifecycle hook functions are compared to vue2

beforeCreate ==> setup()

created ==> setup()

beforeMount ==> onBeforeMount

Mounted ==> onMounted

beforeUpdate ==> onBeforeUpdate

updated ==> onUpdated

beforeDestroy ==> onBeforeUnmount

destroyed ==> onUnmount

errorCaptured ==> onErrorCaptured

3.10 Provide and Inject

  1. Vue3 provides provide and Inject dependency injection for communication between components
  2. Vue3 provides provide and Inject that can be used to awaken communication across multiple levels of components

Father the son:

Parent component passes money to child component template: <h1> My money: {{money}}</h1> child <Demo></Demo> import {provide} from 'vue' setup() {const money = ref(100) // Parent passes data to child provide('money', money) return { money } }Copy the code
Money import {inject} from 'vue' const money = inject('money')Copy the code

Child the parent:

The parent component: Setup () {const money = ref(100) // Define events to pass to child components const changeMoney = (m) => {money.value = m} provide('changeMoney', changeMoney) return { money } }Copy the code
<button @click= "fn" > </button> Setup () {const changeMoney = inject('changeMoney') const fn = () => {// Call event of parent component, ChangeMoney (200)} return {fn}}Copy the code

You can still pass values using props, but the subcomponents are a little different

Setup (props) {console.log(props)} props: {money: Number }Copy the code

3.11 Template REF used

  1. To get a reference to an element or component instance within a template, declare a ref in setup() and return it as usual
Template: Ref <h1 ref="hRef"></h1> setup() {const hRef = ref(null) onMounted() {console.log(hRef. Value)} return { hRef } }Copy the code