This is my eighth day of the August Genwen Challenge

preface

Hi, everybody, I’m Helu.

The last article took you to understand some basic usage of Vue, only to master some basic usage is not enough, but also need to have a deeper understanding, so today’s article let’s talk about the advanced Vue, nonsense not to say, began to dry up!


A, components,

Components are one of the most powerful features of vue.js. It extends HTML elements and encapsulates reusable code.

Component systems allow us to build large applications with individual reusable components. The interface of almost any type of application can be abstracted as a component tree:

In order to be used in templates, these components must first be registered for Vue to recognize. There are two types of registration for components: global and local.

When registering a component, we always need to give it a name. There are two ways to define component names: kebab-case(short dash name) and PascalCase(uppercase name)

When defining a component with a dash delimited name, for example: ‘my-component-name’, you must use dash delimited names when referencing the custom element, for example. When defining a component with an uppercase name, such as ‘MyComponentName’, you can use both nomenclature when referring to the custom element. Both are acceptable.

1. Local components

Using a locally registered component is called a local component, as shown in the following example (the code follows the previous example, if necessary, please send me a private message)

<template>
  <div class="hello">... <! -- Use components --> <Navbar></Navbar> </div> </template>

<script>
export default {
  name: 'HelloWorld'.// Define local components, where multiple local components can be defined
  components: {
    // The component name
    'Navbar': {
      // The contents of the component
      template: '
      
  • Home
  • Student Management
'
}},... } </script>Copy the code

You can see that the page has rendered data, indicating that the component is successfully registered.

2. Global components

Components created using Vue.com Ponent are called global components and can be used in the template of any newly created Vue root instance (New Vue) after registration.

Vue.component('component-a', { / *... * / })
Vue.component('component-b', { / *... * / })
Vue.component('component-c', { / *... * / })

new Vue({ el: '#app' })
<div id="app">
  <component-a></component-a>
  <component-b></component-b>
  <component-c></component-c>
</div>
Copy the code

2. Custom instructions

In addition to the core directives set by default (V-model and V-show), Vue also allows the registration of custom directives. Also divided into global registration and local registration;

Example code is as follows:

// Register a global custom directive 'V-focus'
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus elements
    el.focus()
  }
})
Copy the code
<template>
  <div class="hello">.<input v-focus />
  </div>
</template>

<script>
export default {
  name: 'HelloWorld'.// Register local custom directives
  directives: {
    focus: {
      // The definition of a directive
      inserted: function (el) {
       // Focus elements
        el.focus()
      }
    },
  ...
}
</script>
Copy the code

The effect is as follows: the input box automatically gets focus.Vue provides five hook functions for custom directives:

  • Bind: the directive is called the first time it is bound to an element and is executed only once. This is where you can perform one-time initialization Settings.
  • Inserted: A bound element, called when inserted into the DOM of the parent node (the parent node is only guaranteed to exist).
  • Update: Called when a component is updated.
  • ComponentUpdated: Called when components and subcomponents are updated.
  • Unbind: called when a directive is unbound from an element, executed only once.

Vue instance lifecycle

Each Vue instance goes through the creation, data initialization, mounting, updating, and destruction processes known as the lifecycle, and functions called lifecycle hooks run during this process, giving users the opportunity to add their own code at different stages.

For example, the Created hook can be used to execute code after an instance is created. There are other hooks called at different points in the instance lifecycle, such as Mounted, updated, and destroyed. The this context of the lifecycle hook points to the Vue instance calling it. Do not use arrow functions on option property or callbacks because arrow functions do not have this.

The official diagram below shows when each hook function executes.A code example is as follows:

<template>
  <div class="hello">.<button @click="update">update</button>
    <h3 id="h3">{{ message }}</h3>

  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return{...message: 'Moonlight by my bed'}},methods: {...show() {
      console.log('Execute show method')},update() {
    this.message = 'Frost on the glass'}},//=== four events during creation
 
    beforeCreate() { // The first hook method executed is executed before the instance is created
    
      // When beforeCreate is executed, the data in data and methods are not yet initialized
    console.log(this.message) //undefined
    this.show() //TypeError: this.show is not a function
   
  },
  created() { // The second hook method to execute
    // created executes with data and methods already initialized!
    // If you want to call methods or manipulate data from data, initially you can only do this in Created
    console.log(this.message) // The moon is shining before my bed
    this.show() // Execute the show method
    
  },
  beforeMount() { // The third hook method to execute
     // beforeMount executes when the template is already edited in memory and has not yet been rendered to the page
    console.log(document.getElementById('h3').innerText) //{{ message }}
   
  },
  mounted() { // The fourth hook method to execute
    console.log(document.getElementById('h3').innerText) // The moon is shining before my bed
    // The template in memory has been rendered to the page and the user can already see the content
  },
    
//=== two events running
  beforeUpdate() { // The moment before the data update
    console.log('What the interface displays:' + document.getElementById('h3').innerText)
    console.log(The message data in 'data 'is: + this.message)
    // beforeUpdate executes when data in memory is updated but the page has not been rendered
  },
  updated() {
    console.log('What the interface displays:' + document.getElementById('h3').innerText)
    console.log(The message data in 'data 'is: + this.message)
    // Updated when executed, the data in memory is updated and the page has been rendered}}</script>
Copy the code

Four, routing,

Routing allows us to access different content through different urls. The Vue Router is the official Router for vue.js, which is deeply integrated with the vue.js core, making it a breeze to build single-page applications using vue.js. Vue.js routes need to be loaded into vue-Router library

A code example is as follows:

1. Enter vue-Router library and compile routes

import Vue from 'vue'
// Import the vue-router library
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HelloRouter from '@/components/HelloRouter'

// Use vue. Use to register the Router plug-in
Vue.use(Router)

// Note: if the path is marked with '/', the jump starts from the root directory. If the path is not marked with '/', the jump starts from the current page
export default new Router({
  routes: [{path: '/'.name: 'HelloWorld'.component: HelloWorld
    },
    {
      path: '/router'.name: 'HelloRouter'.component: HelloRouter
    },
  ]
})
Copy the code

2. Use route hops

<template> <div id="app"> <img src="./assets/logo.png"> <p> <! -- Use the router-link component to navigate. -- Specify the link by passing in the 'to' attribute. -- <router-link> is rendered as a '<a>' tag by default --> <router-link to="/"> home </router-link> <router-link To ="/router"> </router-link> </p> <! -- Routing exit --> <! <router-view></router-view> </div> </template>Copy the code

The code example is as follows: The implementation effect is as follows, you can see that clicking the corresponding position can jump.

5. State management

Large applications often grow in complexity as state is scattered across many components and interactions between components. To solve this problem, Vue offers Vuex.

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.

Vuex can help us manage shared state, but it also comes with more concepts and frameworks. If you don’t plan to develop large single-page applications, Vuex can be cumbersome, so use it according to the complexity of the project.

Vuex contains five core concepts: State, Getters, Mutation, Actions, and Modules

1. State

Single state tree. Vuex uses a single state tree that contains all application-level states in a single object. Each application will contain only one store instance.

2. Getters

Vuex allows us to define “getters” (you can think of them as computed properties of the store) in the store. Just like evaluating properties, the return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes.

3. Mutations

The only way to change the state in Vuex’s store is to commit mutation. Mutation in Vuex is very similar to events: each mutation has a string event type (type) and a callback function (handler), so mutation must be a synchronization function.

4. Actions

Action is similar to mutation, except that:

  • The Action commits mutation rather than a direct state change.
  • Actions can contain any asynchronous operation.

5. Modules

Because of the use of a single state tree, all the states of an application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated. To solve these problems, Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules.

A code example is as follows:

1. Create a store directory and write store.js

import Vue from 'vue'
import Vuex from 'vuex'

Use to register the use of the Vuex plugin
Vue.use(Vuex)

export default new Vuex.Store({
  // The state object for global access to set
  state: {
    // The initial property value to set
    count: 0,},// Monitor state changes in real time
  getters: {
    getCount(state) {
      return state.count
    },
  },

  mutations: {

    addCount(state, num) {
      state.count = state.count + num
    },

    delCount(state, num) {
      state.count = state.count - num
    },

  },
})
Copy the code

2. Mount store in main.js3. Use it on the page

<template>
  <div class="hello">.<h3>{{this.$store.state.count}}</h3>
    <h3>{{this.$store.getters.getcount}}</h3>
    <h3>I'm from... Count: {{count1}}</h3>
    <h3>I'm from... {{getCount}}</h3>

    <!--修改 count 值的操作部分-->
    <button @click="add">+</button>
    <button @click="del">-</button>

  </div>
</template>
<script>
  / / introduce axios
  import axios from 'axios'
  // Use vuex's auxiliary function, which needs to be introduced
  import {mapState, mapGetters, mapActions} from 'vuex'

export default {
  name: 'HelloWorld'.add() {
      this.$store.commit('addCount'.1)},del() {
      this.$store.commit('delCount'.1)}},computed: {
      // By cooperating with... Expand the symbol. mapState({count1: state= >state.count }), ... mapGetters(['getCount'])}}</script>
Copy the code

The realization effect is shown in the figure below:When using Vuex, js runs in memory. When the page is refreshed, the page reloads the vUE instance and the data in vuex is reassigned. Solution: moving state object into to the sessionStorage/localStorage.

Six, axios

Axios is a vUE independent project that builds on Promise as an HTTP client for browsers and Node.js and has the following uses:

  • The ajax request can be sent in the browser
  • You can send requests to remote interfaces in Node.js

A code example is as follows:

<script>
  / / introduce axios
  import axios from 'axios'

export default {
  name: 'HelloWorld'.methods: {
 
    getAnswer() {
      var vm = this
      // Send a get request
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
          vm.answer = 'Net can't find API.' + error
        })
    },
    updateAnswer(){
      // Initiate a POST request
      axios({
        method: 'post'.url: 'http://localhost:8082/admin/edu/teacher/' + this.teacher.teacherId,
        data: this.teacher
      }).then(function (response) {
        console.log(response)
        console.log('Modified successfully')
      }).catch(function (error) {
        console.log(error)
      })
    },
  },

}
</script>
Copy the code

conclusion

Ok, that is today’s lesson content, this paper Outlines the Vue lifecycle, components, custom orders, and the use of some tools library, I believe you had a deeper step of Vue met, learned the basic project in field, could be in real projects to add their own use and understanding, can in work.

Thank you for reading, if there is any deficiency, please forgive me, welcome to leave your original opinion in the comments section, thank you!