Vue3.0 is different from 2.0

Compared with Vue2.0, Vue3.0 has the following advantages: faster, smaller, easier to maintain, easier to native, and more fun for developers;

faster

  1. – Virtual DOM completely reworked, Mounting & Patching increased speed by 100%
  2. More compile-time reminders to reduce runtime overhead;
  3. Based on Proxy observer mechanism to meet full language coverage and better performance;
  4. Ditch Object.defineProperty in favor of a faster native Proxy
  5. Component instance initialization speed increased by 100%; (Double speed)
  6. Double speed/half memory usage; (Memory halved)

Are more likely to maintain

  1. 3.0 has new TypeScript and PWA support and some commands have changed:
  2. NPM install -g vue@cli
  3. Delete vue list
  4. Create the project vue Create
  5. Start the project NPM Run Serve
  6. The default project directory structure has also changed:
  7. Remove configuration file directories, config and build folders
  8. Remove static folder, add public folder, and move index.html to public
  9. The views folder has been added to the SRC folder for sorting view components and public components

smaller

  1. Tree-shaking is friendlier;
  2. New Core Runtime: ~ 10KB gzipped;

Easier acoustic

PWA stands for Progressive Web App, or Progressive Web application. A PWA application is first and foremost a Web page, and a Web application can be written using Web technology. Then add the App Manifest and Service Worker to realize the installation and offline functions of PWA. PWA can put the shortcut of App on the desktop and run in full screen, which is the same as the original App

New methods and new writing methods in 3.0

The role of the setup

To compare how vue2.0 works, you need to use data, Method, computed, Watch, and life cycles in setup functions

How to use data in setup?
import { ref, toRefs, reactive }  from 'vue'
export default {
  name: 'Test'.setup(){
    // Setup defines the reactive variables used by the template. You need to define them by ref or reactive
    // Ref is a factory class. The input parameter is the value of the initialized variable. It is not confused with the ref concept of the component
    // Define a single variable. To make sense, I compare it with vue2.0
    // Vue2.0, whether we define a single or multiple we define in data, such as:
    /* data(){ return { name: 'zhangmin' } } */
    
    In Vue3.0, if you only need to define a reactive variable, you can use the following ref
    // Let, var, const; // Let, var, const; // Let, var, const
    const name = ref('zhangmin')
    // How to obtain the value of name from the.value of the variable defined
    
    console.log('Get name value:', name.value)
    
    // To check whether a value is responsive, use isRef
    // Use.value every time to get a value. // Use.value every time to get a value
   // Reactive creates a reactive data object
    const data = reactive({
       name: 'My name is Zhang Minjun.'.sex: 'Gender matters'.arr: []})// But there is a drawback. If you put data directly in return,
    
      
{{data.sex}}
// You say you can deconstruct it in return {... Data} If you do that, all the data inside will become non-responsive, // Vue3.0 provides a way to satisfy your fantasy: toRefs. With this wrapper, you can use deconstruction in return // Wrap the data above const refData = toRefs(data) // There is always a return in data, which is also required here, but where all methods evaluate attributes through this return // Can I define a variable directly on this return? The answer is yes, but the defined variable is not reactive and cannot be changed return { ...refData, // You can also use... ToRefs (Data) is a little easier name, rules: [] // If you have data that does not change, such as rules or configurations, you can define it directly here without having to use refs and reactive}}}Copy the code

2. How to use method in setup?

import { ref } from 'vue'
export default {
  name: 'Test'.setup(){
    // Define a reactive data
    const baby = ref('1岁boby')
   // Define method and return the name of the method in return
   // Note: here we use call-responsive data, that is, the data you defined for Vue2.0,
   // This is not allowed. The new setup function is created for vue2.0's beforeCreate and created functions.
   // It's going to run from the start, there's no reference to this yet, it's undefined, and all the responsive variables that you define need to be called.value
    const wantToKnowBabysName = () = > {
      console.log("oh,he is a " + baby.value)
    }
    const getData = () = > {}
   / / contrast vue2.0
   /* method: { wantToKnowBabysName(){ console.log("oh,he is a " + baby.value) }, getData() { } } */
   
    return {
      baby,
      wantToKnowBabysName,
      getData
    }
    
  }
}
Copy the code

3. How do I use computed in SETUP?

// Be careful to use computed
import { ref, computed} from 'vue'
export default {
  name: 'Test'.setup(){
    // Define a reactive data
    const baby = ref('Quack quack')
    // Define cuihua age
    const age = ref(28)
    // A callback function is passed for computed attributes
    const areYouSureYouAreABaby = computed(() = > {
      return `I'm sure,I'm a 300 month baby, ${baby.value}`
    })
    // Set and get
    const setAge= computed({
      get() {
        return age.value + 10
      },
      set(v) {
        age.value = v - 10}})/ / contrast vue2.0
   /* computed: { areYouSureYouAreABaby (){ return `I'm sure,I'm a 300 month baby, ${baby.value}` }, setAge:{ get(){ return age + 10 }, set(v) { age = v - 10 } } } */
   
    return {
      baby,
      age,
      areYouSureYouAreABaby 
    }
    
  }
}
Copy the code

4. How to use Watch in setup?

// Use watch
import { ref, watch, watchEffect } from 'vue'
export default {
  name: 'Test'.setup(){
    // Define a reactive data
    const baby = ref('Quack quack')
    const arr = ref(['cui flower'.'little red'])
    // There are two ways to listen for a value
    // Watch takes three parameters: the first is a getter, the second is a callback, and the third is options.
    // open ref ()
    watch(baby, () = > {
      return `I'm sure,I'm a 300 month baby, ${baby.value}`
    })
   // Add the value of ref
   watch(() = > baby.value, () = > {
      return `I'm sure,I'm a 300 month baby, ${baby.value}`
    })
  
   // When listening for multiple values, the first argument is an array containing the listening elements
   watch([baby,arr], (v, o) = > { 
     / / here v, o is an array, so when you value v [0], v [1] to which the change of the element. }, {deep: true.immediate: true
   })
 // or write it as
 watch([baby,arr], ([baby, arr], [prebaby,prearr]) = >{... })/ / contrast vue2.0
   /* watch: { baby(v, o) { }, arr: { handle(v,o) {}, deep: true, immediate: true, flush: 'pre' / / there are three parameters, the default 'pre' | 'post' | 'sync' default 'pre' component update before operation, after the 'post' component rendering, commonly used for you need to visit the $ref can use this, 'sync' is used whenever your value changes and you need to execute a callback synchronously
   $watch = vue2 $watch = vue2 $watch
  Vue3.0 watchEffect
  // watchEffect takes two arguments, one is a side effect function, and the other is options ().
// In Vue2.0, we usually add some listener events to Created, such as your $bus event listener, which can be written in setup
watchEffect((onInvalidate) = > {
   // If the age changes, the listener will be triggered
   // This is done immediately after the component is created
   const _age= `her age is ${age.value}`
   console.log(_age)
   // Sometimes you need to mount some listener events here
   const handerClick = () = >{}
   document.addEventlistener('click', handerClick)
   // In Vue2.0 we need to remove it when destroying, and we provide a method called the onInvalidate callback to solve the remove problem
   onInvalidate(() = >{
       /* Execution timing: When the side effect is about to be re-executed, this is executed first each time the watchEffect callback is executed, or when the component is uninstalled if watchEffect is used in setup() or lifecycle hook functions. * /
       document.removeEventListener('click',handerClick )
    })  
})
// This also supports async,await
const data = ref(null)
watchEffect(async onInvalidate => {
 // Suppose an interface gets data
  data.value = await fetchData()
  onInvalidate(() = > {...})
})
Options: Flush,onTrigger,onTrack
watchEffect(onInvalidate= > {
  onInvalidate(() = > {...})
}, {
  flush: 'pre' // Like watch, pre is called by default before component updates
  onTrigger(e) {
    // this is triggered when the dependency's set is triggered
  },
  onTrack(e) {
    This is triggered when the dependency gets called}})return {
      baby,
      areYouSureYouAreABaby,
      data 
    }
    
  }
}
Copy the code

How to use the lifecycle in Setup?

// Import components with what

import {onBeforeMount
       ,onMounted
       ,onBeforeUpdate
       ,onUpdated
       ,onBeforeUnmount
       ,onUnmounted} from 'vue';
export default {
  setup: function () {
    // Before the component is mounted
    onBeforeMount(() = >{
      console.log("onBeforeMount");
    });
    // The component is mounted
    onMounted (() = > {
      console.log("onMounted");
    });
    // Data update, virtual DOM before patch
    onBeforeUpdate (() = > {
      OnBeforeUpdate and onUpdated do not modify values.
      console.log("onBeforeUpdate");
    });
    // Virtual DOM rendering is complete
    onUpdated (() = > {
      console.log("onUpdated");
    });
    // Before the component is destroyed
    onBeforeUnmount (() = > {
      console.log("onBeforeUnmount");
    });
    // After the component is destroyed
    onUnmounted (() = > {
      console.log("onUnmounted"); }); }}Copy the code

This section describes vue3.0 attributes

Reactive and ref

Reactive is used to add reactive state to objects. Receives a JS object as an argument and returns a copy of the responsive state.

Ref is used to add reactive state to data. Reactive can only pass in parameters of object types, whereas ref can only be used to add reactive state to basic data types. Value is required when retrieving data values. Refs are implemented by wrapping a layer of objects with value properties around reactive

Parameters can be passed to any data type, and object types can be passed to remain deeply responsive, so the applicability is wider. Ref is recommended when defining data in VUE 3.0 Setup to facilitate logical separation and service decoupling

The code is as follows:

<template>
       <div> Count is: {{ state.count }}</div>   
       <div> name is: {{ name }}</div>   
       <div> num is: {{ num.count }}</div>   
</template>

<script>
import { reactive,ref} from "vue"
export default {
    setup() {
     const state = reactive({
          count: 0});// Add reactive state for basic data types
        const name = ref("Neo");

        // Add reactive state for complex data types
        const num = ref({
          count: 0});return {
         state,name,num
        }
    }
}
</script>

Copy the code

At this point we can also implement a simple addition, which is to introduce again a computed property of vue, computed has to import, if it doesn’t import it, it will report an error, computed doesn’t exist

The following code

<template>
       <div> Count is: {{ state.count }} double:{{state.double}}</div>   
</template>

<script>
import { reactive,computed} from "vue"
export default {
    setup(){
     const state = reactive({
          count: 0.double: computed(() = > state.count * 2)});return {
         state
        }
    }
}
</script>
Copy the code