Summary of Vue3 learning

1. Create Vue3 single page application project

There are two official ways to quickly create SPA projects:

  • Create projects based on vite (small and clever, only Vue3.x is supported)
  • Create projects based on Vue cli (large and comprehensive, supporting Vue2.x and Vue3.x)

2. template node

  • Vue2.x only supports one root node
  • Vue3.x supports multiple root nodes, so it can be wrapped without a div

3. Dynamically bind the class name to the element

  • Dynamically bind a single class name to an element through a ternary expression:
view code
<h3 class="thin" :class=" isItalic ? 'italic' : '' ">content</h3>
<button @click="isItalic=!isItalic">Toggle Italic</button>

data( ) {
         return { isItalic: true }
}

.thin {   // Font thinning
   font-weight:200;
}
.italic {  // Tilt font 
    font-style: italic;
}
  • Dynamically bind multiple class names to elements through array format:
view code
<h3 class="thin" :class="[ isItalic ? 'italic' : ' ', isDelete ? 'delete' : ' ' ]">MyDeep</h3>

<button @click="isItalic=!isItalic">Toggle Italic</button>
<button @click="isDelete=!isDelete">Toggle Delete</button>

data( ) {
    return {
      isItalic: true, 
      isDelete: false. 
}
  • Dynamically bind multiple class names to elements through object format:
view code
<h3 class="thin" :class="class0bj">MyDeep</h3>
<button @click="class0bj.italic =! classObj.italic">Toggle Italic</button>
<button @click="class0bj.delete =! classObj.delete">Toggle Delete</button>

data( ) {
  return {
     class0bj:{  // Object, the attribute name is the class name, and the value is a Boolean value 
         italic: true, 
         delete: false,
}

4.: style binding

You can set the style attribute to an element as an object.

view code
<template>
  <div :style=" backgroundColor: bgcolor,fontSize: fSize + 'px' ">{{ title }}</div>    
</template>

<script>
export default {
  props:{
      title:{
          type: String,
          default: 'title'
      }
      bgcolor:{
          type: String,
          default: red
      }
      fSize:{
          type: Number,
          default: 12
      }
}
</scripe>

5. Verification of prop attribute

  • For basic type checking, you can directly specify the basic verification type for the prop attribute of the component, so as to prevent the user of the component from binding data of the wrong type
view code
export default {
props: {  // 8 basic types supported
   propA: String. // String type 
   propB: Number, // Number type 
   propC: Boolean,// Boolean type
   propD: Array, // Array type 
   propE: Object, // object type 
   propF: Date, // Date type 
   propG: Function,// Function type
   propH: Symbol // Symbol type 
}
  • Customize the validation function to control the value of prop attribute more accurately
view code
export default {
props: {
// Define the "validation rule" of propD attribute in the form of "configuration object" 
    propD:{
        // The value of propD attribute can be verified through the validator function, and the "value of attribute" can be received through the formal parameter value 
        validator(value){
             // The value of the propD attribute must match one of the following strings
             // The return value of the number of validator paintings is true, indicating that the verification passed, and false indicating that the verification failed 
            return ['success', "warning", 'danger'].indexof(value)!== -1
        }
    }
}

6. Custom event emit node

Vue3. In X, custom events encapsulated by developers for custom components must be declared in the emits node in advance!

3 steps for using custom events (Vue3 new declaration steps):

(1) When packaging components:

  • Declare custom events
  • Trigger custom event

(2) When using components:

  • Listen for custom events
view code
<template>
   <button @click="onBtnClick">+1</button>
</template>

<script>
export default {
   emits: ['change'],
   methods:{ 
      onBtnClick( ){
          this.$emit('change',this.count)// When a user-defined event is triggered, the parameter is passed through the second parameter
      }
    }
}
</script>

7. Bidirectional data synchronization between parent and child components

If two-way data synchronization is realized between parent and child components, v-model: is used on the component to bind customization.

view code
// Farther.vue
// By binding v-mode to custom attributes
<Son v-model:number = "num"></Son>

data:{
    num:0
}

// Son.vue
// 
props: ['number']
emits: ['update:number']  // update is a fixed writing method, which requires two-way synchronization for number
 add (){
     this.$emit('update:number',this.number + 1)
}

8. Communication between sibling components

Vue3. The scheme of data sharing between brother components in X is the same as vue2 As in X, the eventbus scheme is used, but in vue3 In X, you can use the third-party package MIT to create eventbus objects.

Install mitt command: npm i mitt

9. Share non responsive data with immediate descendants

When the parent node's components share non responsive data with its descendant components, the nested relationship between components is complex. provide and inject can be used to realize data sharing between descendant components.

  • Parent components share data through provide
  • The subcomponent receives data through inject
view code
// parent.vue
export default {
data( ) { 
    return {
      color:"red"  // 1. Define the data to be shared by "parent component" to "child component"
    },
},
provide( ) {   // 2. The object of the provide function return contains "data to be shared with descendant components" 
    return {
      color: this.color,
    }
}
// ----------------------
// son.vue
<template>
    <h5> {{ color }} </h5>
</template>

<script>
export default {
       //The descendant component uses inject to receive the color data shared downward by the parent node and use it on the page
        inject: ['color']
}
</script>

10. Share responsive data with immediate descendants

  • When the parent node uses provide to share data downward, it can share responsive data downward in combination with the calculated function
  • If the parent node shares responsive data, the descendant node must value
  • Responsive data means that the data of the parent component changes and the data received by the child component also changes
view code
// parent.vue
// 1. Import the computed function from vue as needed
import { computed } from "vue" 

export default {
data( ) {
    return { color: 'red' }
}. 
provide( ) { 
    return {
    // 2. Using the computed function, you can package the data to be shared as "responsive data"
      color: computed(() => this.color), 
    } 
}

--------------------------
// son.vue
<template>
<!-- Responsive data must be in value Use in the form of -->
<h5> {{ color.value }} </h5>
</template>

<script>
export default {
// Receive the color data shared downward by the parent node and use it on the page 
     inject: ['color']
}
</script>

11. Vue2 and Vue3 global configuration axios

Vue2 global configuration axios:

In the project of vue2, the global configuration of axios needs to be in main JS entry file, configure axios globally through the prototype object of Vue constructor.

Install Axios: NPM I Axios - S

view code
// main.js
import Vue from 'vue'
import App from'./App.vue3 

// 1. Import axios
import axios from 'axios'

// 2. Configure request root path
axios.defaults.baseURL ='https://www.escook.cn'
// 3. Configure axios globally through the prototype object of Vue constructor
Vue.prototype.$http = axios

new Vue({
    render: h => h(App),
}).$mount('#app')

Vue3 global configuration axios:

Install Axios: NPM I Axios - S

Then in main JS entry file, through app config. Globalproperties globally mounts axios.

view code
// main.js
// Import axios
import axios from 'axios'

// Split the app creation instance and write it
const app = createApp(App)

// Request and path for axios configuration item
axios.defaults.baseURL = 'https://www.escook.cn'

// $http can be customized. Members inside the simulation official here start with $
app.config.globalProperties.$http = axios 

app.mount('#app')
-------------------------------------
// Use this on the component$ http. Get can initiate a request
<button type="button">launch GET request</button>
<script>
export default { 
name:'GetInfo', 
methods: {
    async getInfo( ) {
          const { data:res } = await this.$http.get(/api/get,{
               params:{
                   name:'ls',
                   age:18
                }
          })
          console.log( res )
    }
}

12. vue-router4. How to create a routing module in version x

Vue2.x with 3 X version of routing, vue3 X 4 X version of the route. 3.x version routing and 4 The biggest difference of X version routing is the difference of creating routing module.

4.x routing creation module:

view code
// 1. On demand import method
import {createRouter, createWebHashHistory } from 'vue-router'

// 2. Import components that need to be switched using routing 
import MyHome from"./Home.vue' 
import MyMovie from'./Movie.vue'

const router -createRouter ({            // 3. Create routing object 
    history: createWebHashHistory(),// 3.1 specify the handover of management routes through hash
    routes: [                                     // 3.2 creating routing rules 
          { path: '/home', component: MyHome },
          { path: '/movie', component: MyMovie },
               ],
})

export default router //          4. Share routing objects outward 

13. axios interceptor

The interceptor is automatically triggered every time an ajax request is made and a response is received.

Main application scenarios of Interceptor:

  • Set Token authentication
  • Setting the Louding effect

Set request interceptor in axios:

Via Axios interceptors. request. Use (successful callback, failed callback) can configure the request interceptor, and the callback failure function can be omitted!

view code
axios.interceptors.request.use(function (config) {
   // Do something before request is sent 
    return config;
}, function (error) {
   // Do something with request error 
    return Promise.reject(error);
})

Set Token authentication:

view code
import axios from 'axios'

axios.defaults.baseURL = 'https://www.escook.cn'

// Interceptor for configuration request
axios.interceptors.request.use(config => {
    //Configure the Token authentication field for the current request
    config.headers.Authorization = 'Bearer xxx'
    return config
})

vue.prototype.$http = axios

Set Loading effect:

With the help of the Loading effect component provided by element UI.

view code
// 1. Import the Loading effect component as needed
import { Loading } from 'element-ui'

// 2. Declare variables to store the instance object of the Loading component
let loadingInstance = null

// Interceptor for configuration request
axios.interceptors.request.use(config => {
// 3. Call the service() method of the Loading component, create an instance of the Loading component, and display the Loading effect in full screen 1
    loadingInstance = Loading.service({ fullscreen: true })
    return config 
})

// Configure response interceptor
axios.interceptors.response.use(request => {
    // 4. Turn off the Loading effect
    loadingInstance.close()
    return response
})

14. proxy cross domain proxy

 

Posted by saurabhdutta on Mon, 18 Apr 2022 14:42:33 +0930