Take beginners to Vue3

Posted by gunabalans on Sat, 11 Sep 2021 00:47:04 +0200

Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

preface

Tip: Here you can add the general contents to be recorded in this article:
With the continuous development of artificial intelligence, machine learning technology is becoming more and more important. Many people have started learning machine learning. This paper introduces the basic content of machine learning.

Tip: the following is the main content of this article. The following cases can be used for reference

1, Why study Vue3?

  • present situation:

    • Vue next issued on September 18, 2020
  • Advantages of Vue3

    • The hottest frame, it is one of the hottest front-end frames in China
    • The performance is improved, and the running speed is about 1.5 times that of Vue2.x
    • Smaller, on-demand compilation volume is smaller than Vue2.x
    • Type inference. Better support TS (superset of typescript = "js")
    • Advanced giving exposes the underlying API and provides more advanced built-in components
    • Option API - combination API can better organize logic, encapsulate logic and reuse logic
  • Vue3 outlook

    • This is a trend. More and more enterprises will certainly upgrade to Vue3.0 in the future
    • For large projects, Vue3.0 can be used for more and more large projects due to its friendliness to Ts.

2, Create vue app

1. Create a project based on Vue scaffolding

The code is as follows (example):

 1. Installation of scaffold
npm i @vue/cli -g
 2. establish vue3 Item (select from options) v3 Version, others as before)
vue create entry name
 3,Switch path
cd entry name
 4,Run project
npm run serve

2: Project code structure analysis

  • Entry file main.js
    The code is as follows (example):
import { createApp } from 'vue'
// Import root component
import App from './App.vue'
// Import routing objects
import router from './router/index.js'
// Import store instance object
import store from './store/index.js'

// app is equivalent to the instance object vm of new Vue() in Vue2
// app.use() indicates the configuration plug-in
// Vue.use(router) Vue2 plug-in configuration
const app = createApp(App)
app.use(store).use(router).mount('#app')
// createApp(App).use(store).use(router).mount('#app')

// Vue2
// import Vue from 'vue'
// const vm = new Vue({
//   router,
//   store,
//   redner: h => h(App)
// }).$mount('#app')
  • Summary:
  1. The instantiation method of Vue has changed: instantiation is based on the createApp method
  2. router and store are configured using the use method
  3. Vue3's typical API style: Import on demand, in order to improve the performance of packaging

3. Root assembly structure

<template>
  <!-- Vue2 Templates for components in must have a unique root node -->
  <!-- Vue3 Templates for components in can have no root node -->
  <div id="nav">
    <router-link to="/">homepage</router-link> |
    <router-link to="/about">about</router-link>
  </div>
  <!-- Fill location of routing component -->
  <router-view />
</template>
  • Summary: the template of a component in Vue3 may not have a root node (the template of a component in Vue2 must have a unique root node)

  • In vue3, a component template can have no root node

  • In vue2, the template of a component must have a root node

4. Routing module analysis

import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

// Vue2 create instance object
// const router = new VueRouter({
//   routes
// })

// Vue3 create instance object
const router = createRouter({
  // Adopt historical API routing mode
  // history: createWebHistory()
  // hash routing mode
  history: createWebHashHistory(),
  routes
})

export default router

5. Advantages: Import on demand

    • The route instance object is created using the createRouter method, which is the typical style of Vu e3
    • There are changes in the way hash and history are used
      • Vue2 adopts the mode option: hash/history
      • Vue3 adopts the following methods: createWebHashHistory()/createWebHistory()
  • The instance object store is created using the createStore method instead of new

  • The biggest advantage of group API is to organize the code structure by function, which is conducive to code reuse

    • API setup function
      • setup is a new component option that serves as a starting point for using composite API s in components
      • From the perspective of component life cycle, its execution is performed before the component instance is created, and vue2.x is executed before create.
      • The beforeCreate/created declaration cycle function in Vue3 has been abandoned and has been replaced by setup
      • This cannot be accessed at this time because the component instance was not created at this time
      • The data returned here is used to provide data and methods to the template, similar to the data in vue2
      • data can still be used in vue3, but it is not recommended,

3. API function of vue3

1. API setup function

  • setup is a new component option that serves as a starting point for using composite API s in components
  • From the perspective of component life cycle, its execution is performed before the component instance is created, and vue2.x is executed before create.
  • The beforeCreate/created declaration cycle function in Vue3 has been abandoned and has been replaced by setup
  • This cannot be accessed at this time because the component instance was not created at this time
  • The data returned here is used to provide data and methods to the template, similar to the data in vue2
  • data can still be used in vue3, but it is not recommended,
<div>
  <div>setup Function usage</div>
  <div>{{msg}} </div>
  <div> <button @click="handleClick"> </button>
</div>
setup(){
  const handleClick=()=>{
    console.log(1111)
  }
  return {
    msg:'hello',
    handleClick:handleClick//Write handleClick directly
  }
}

2. Component API life cycle

  • Review the vue2.x lifecycle hook function:
    • beforeCreate
    • created
    • beforeMount
    • mounted
    • beforeUpdate
    • updated
    • beforeDestroy
    • destroyed
  • Understanding vue3.0 life cycle hook function
    • setup before creating an instance
    • onBeforeMount before mounting DOM
    • onMounted after DOM is mounted
    • onBeforeUpdate before updating components
    • onUpdated after updating the component
    • onBeforeUnmount uninstall before destroy
    • onUnmounted after uninstallation and destruction
setup(){
   onBeforeMount(()=>{
    console.log()
   })
   onBeforeMount(()=>{
    console.log()
   })
}
  • Summary: 1:Vue3 lifecycle function has changed

  • 2: Remove two, beforeCreatea and created, and add setup

  • 3: The method name has changed. There is an on in front of the method name and a hump in the middle

  • 4: Lifecycle changes of unloaded components: onBeforeUnmount, onUnmounted

  • 5: The same life cycle can trigger multiple times

  • 3. Data response

    • 1. Combine API reactive functions

      • reactive is a function that can define a complex data type and become responsive data.
      • The normal data returned by setup by default is not responsive
      • If you want the data to be responsive, one way is to wrap the data with a reactive method
    • <template>
        <div>
          <div>Data response</div>
          <hr>
          <div>{{obj.msg}}</div>
          <div>
            <button @click='handleClick'>click</button>
          </div>
        </div>
      </template>
      <script>
      import {reactive} from 'vue'
      export default {  
        setup(){
      //Data response, the change of data leads to the automatic change of view
         const obj=reactive({
          msg:'hello',
          info:'hi'
          })
         const handleClick=()=>{
          obj.msg="nihao"
         }
         return{
         msg:obj.msg,
         handleClick
          }
        }
      }
      </script>
      
      • 2. Combine API toref functions

        • Define responsive data:

          • toRef is a function that converts an attribute in a responsive object into individual responsive data, and the value is associated.
        • Requirement: the obj prefix does not need to be added in the template, but the attribute is directly obtained

        import {reactive,toRef}
        const obj=reactive({
            msg:'hello',
            info:'hi'
           })
        // Take out a single attribute in the object and ensure the responsiveness of the data
        const msg=toRef(obj,'msg')
        const info=toRef(obj,,'info')
        
         const handleClick=()=>{
          obj.msg="nihao",
          obj.info = 'coniqiwa'
         }
         // If the object attribute in reactive is re assigned, it will lose the responsiveness
         return{msg,info,handleClick}
        
        • 3. Combine API torefs functions

          • toRefs is a function that converts all attributes in a responsive object into responsive data. It is usually used to deconstruct a reactive definition object.
          import {reactive,toRefs}
          setup(){
            //The obj prefix must be added to the template, but the attribute must be obtained directly
            //The data in the object wrapped by the reactive method is reactive
            const obj=reactive({
              msg:'hello',
              info:'hi'
             })
              // Take out a single attribute in the object and ensure the responsiveness of the data
              // const msg = toRef(obj, 'msg')
              // const info = toRef(obj, 'info')
              // Structure the attributes in obj object to ensure the responsiveness
          const{msg,info}=toRefs(obj)
          const handleClick=()=>{
            obj.msg="nihao"
            obj.info="lalala"
           }
          // If the object attribute in reactive is re assigned, it will lose the responsiveness
           return{msg,info,handleClick}
          }         
          
      • 4. Combine API ref functions

        • The ref function is commonly used for simple data types, which are responsive data. It is generally used for simple data types and can be defined using Ref

          • . value is required when modifying and obtaining values
          • Use the response data declared by ref in the template. You can omit. value
        • However, value is required to access the template

        • <div>Data response</div>
             <hr>
             <div>{{count}}</div>
            // However, value is not required to access in the template
             <div> {{msg}} </div>
             <div>
               <button @click='handleClick'>click</button>
           </div>
          import {ref} form 'vue'
          const count =ref(0)
          const obj = ref({ msg: 'hello' })
          const handleClick=()=>{
            //ref defined data, in js 🀄 ﹥ the operation needs to be performed through the value attribute
             // However, value is not required to access in the template
               count.value+=1
            console.log(obj.value.msg)
          }
          return {count,handleClick}
          
    • 5. Summary of data response

      • The ordinary data returned directly in setup is not responsive
      • Wrap objects with reactive can become responsive data
      • To simplify access to objects (without prefixes), you can use toRef for optimization
      • To get multiple properties of an object. You can use toRefs for simplification
      • If it is a simple data type. In fact, the definition of ref is more appropriate
  • 6. Combine API computed functions

  • 1. Basic usage of calculation attributes

    • Application scenario: calculate a data based on the existing data

    • The callback function must return, and the result is the result of the calculation

    • If the calculation attribute depends on

    • Asynchronous operation is not allowed because return cannot return the result of one step

    • The value of the calculated property is read-only and cannot be modified

    • <div @click="age">{{age}}</div>
      <div>{{nextAge}}</div>
      import {ref,computed} form 'vue'
        setup(){
          const age=ref(10)
          const nextAge=computed({
              // The callback function must return, and the result is the result of the calculation
            // If the data on which the calculation attribute depends changes, it will be recalculated
            return age.value + 1
           },
         )
         return {age,nextAge}
      }
      
      
  • Modify the value of the calculated attribute
    <div @click="age">{{age}}</div>
    <div>{{nextAge}}</div>
    import {ref,computed} form 'vue'
      setup(){
        const age=ref(10)
        const nextAge=computed({
            // The callback function must return, and the result is the result of the calculation
          // If the data on which the calculation attribute depends changes, it will be recalculated
          get () {
            // If the value of the calculated property is read, the get method is called by default
            return age.value + 1
          },
          set (v) {
            // If you want to modify the value of the calculated property, the set method is called by default
            age.value = v - 1
          } 
          return age.value + 1
         },
       )
       return {age,nextAge}
    }
    

    Summary:

    1. Calculation properties can be read or modified directly

    2. If you want to modify the calculated attribute, the calculated argument should be an object

      • Read data trigger get method

      • Modify the data to trigger the set method. The formal parameter of the set function is the value you assigned to it

  • 7. Combine API watch functions

    • The watch function is used to define the listener
    • When the intercepted information changes, trigger the listener to return the function
    • After the routing parameters change, call the interface again to read the component data
    • Monitor data changes based on listeners
    • The intercepted data must be responsive
    1: Listen for responsive data defined by ref
    • // Listener = base type
      import {ref,watch} from 'vue'
      setup(){
        // Listen for basic usage of common values
      const count =ref(0)
       watch(count,(newValue,oldValue)=>{
         console.log(newValue, oldValue)
       })
      }
      
      • Summary: listening to common data can obtain the values before and after modification; The intercepted data must be responsive.

        2: Listen for reactive data defined by reactive

      • const obj =reactive({
           msg:'tom'
        })
        //Listening object 
        // Listening object
        // watch(obj, (newValue, oldValue) => {
        //    console.log(newValue === oldValue)
         // }
        watch(obj,()=>{
          console.log(obj.msg)
        })
        const handleClick=()=>{
          obj.msg='jw'
        }
        
        
        • Summary: if you listen to an object, the two parameters of the listener's callback function are the same, indicating the latest object data. At this time, you can also directly read the listened object, and the obtained value is also the latest.

        3: Listen for multiple response data

        //Listen for multiple values
        const n1=ref(1)
        const n2=ref(2)
        watch([n1,n2],(v1,v2)=>{
          console.log(v)
          // Both v1 and v2 are arrays
          // v1 represents the latest value of all the values being monitored
          // v2 represents the original value of all the monitored values
        })
        const handleClick=()=>{
          obj.msg='jj'
          n1.value=3
          n2.value=4
        }
        // Listen
          const stuInfo=reactive({
            uname:'lili',
            age:12
          })
          // If you are listening for an expression, you need to use a function
          watch(()=>stuInfo.age,(v1,v2)=>{
             console.log(v1,v2)
          })
          const handleClick=()=>{
            
          }
        
        • Summary: the values before and after the update can be obtained; The listening result is also an array, and the data order is consistent

        4: Listen to a property of reactive defined responsive data

        // 4. Listen for a property in the object
        // If there is an attribute in the listening object, you need to use the function mode
        watch(() => obj.age, (v1, v2) => {
          console.log(v1, v2)
        })
        
        • Summary: if you listen for an attribute in an object, you need to use the function method. Listening for less data is conducive to improving performance.
      • watch method configuration options

        // watch(obj, (o1, o2) => {
        //   //If you listen to the object, the values of parameters o1 and o2 are the same and are the latest values
        //   console.log(obj)
        // }, {
        //   //The component is triggered once the first time it is rendered
        //   immediate: true
        // })
        
        // If the monitored data is a long expression, you need to use a function
        // However, after being written as a function, the familiar changes in the inner layer cannot be heard, so the deep option needs to be added
        watch(() => obj.friend, (o1, o2) => {
            // If you listen to the object, the values of parameters o1 and o2 are the same and are the latest values
            console.log(obj)
        }, {
            // The component is triggered once the first time it is rendered
            immediate: true,
            // Deep listening. If the data in the object changes, it will also be listened to
            deep: true
        })
        
      • Immediate: true means that the component is triggered once immediately after rendering, that is, it is called immediately

      • Deep: true deep listening, listening for sub attributes in the object. The monitored content needs to be the writing method of the function

  • 8. Combine API ref attribute

    The ref attribute can be used to obtain DOM or component instances. The writing method needs to be distinguished from vue2.0

    • Operate ref – array scene based on Vue2

      <ul>
        <li v-for="(item, index) in list" ref="fruits" :key="index">{{ item }}</li>
        <!-- <my-com :key='index' v-for='index in 8' ref='info'></my-com> -->
      </ul>
      <button @click="handleClick">click</button>
        methods: {
          handleClick () {
            const fruits = this.$refs.fruits
            console.log(fruits[1].innerHTML)
          }
        }  
      // Batch bind refs with the same name (mainly refs used in v-for scenarios). At this time, the value accessed through [this.$refs. Name] should be an array containing each DOM element
        // The ref binding component is used similarly
      
      • Vue3 operates ref in the same way

             <div>
                // vue3 binding ref
                user name :<input type="text" ref='uname'>
                       <button @click='handleClick'>click</button>
                <ul>
                 // Batch binding of ref s in Vue3 is not allowed
                  <li ref='fruits' :key='index' v-for='(item, index) in list'>{{item}}</li>
                </ul>
              </div>
        
            import { ref } from 'vue'
             setup () {
                // 1. Create a reference object
                const uname = ref(null)
                const handleClick = () => {
                  // Get the method of DOM element uname.value
                  console.log(uname.value.value)
                }
                return {
                  // 2. Provide the ref object to the template
                  uname,
                  handleClick
                }
              }
            vue3 Yes, No this,out of commission this.$refs.info.innerHTML
            this.$refs.fruit The value of should be a li Instance array DOM element Vue2 Can be operated directly in DOM And components
        
      • Get the DOM or component traversed by v-for

      • <div id="nav">
           <div>Vue3 Basics-ref Direct operation DOM-Batch binding</div>
           <ul>
             <li :ref='setDoms' v-for='(item, index) in list' :key='index'>{{item}}</li>
           </ul>
           <button @click='handleClick'>click</button>
         </div>
        import { ref } from 'vue'
         setup () {
            // Put the batch bound DOM into the array
            const fruits = []
            // Batch operation DOM elements
            const list = ref(['apple', 'orange', 'peach'])
            const handleClick = () => {
              console.log(fruits[1].innerHTML)
            }
            // For the scenario of batch binding ref, a function needs to be bound
            // And the function needs dynamic binding in the template (a single DOM does not need dynamic binding)
            const setDoms = (el) => {
              // The parameter el represents a single DOM element bound
              fruits.push(el)
            }
            return { handleClick, list, setDoms }
          }
        
        • Summary: process of ref batch operation elements

          1: Define a function,

          2: Bind the function to ref (it must be bound dynamically)

          3: In function

summary

Tip: here is a summary of the article:
For example, the above is what we want to talk about today. This paper only briefly introduces the use of pandas, which provides a large number of functions and methods that enable us to process data quickly and conveniently.

Topics: Javascript Front-end Vue Vue.js