Vue 2.0 Foundation


Vue 2.0 Foundation

Knowledge points

  1. characteristic
  2. example
  3. Basic grammar
  4. life cycle
  5. Route management Vue router
  6. Status management vuex
  7. HTTP request library Axios


1. It is an MVVM framework

Derived from MVC architecture, it is divided into view (view layer), ViewModel (data view layer) and model (data layer). The most iconic feature of MVVM is data binding to realize data-driven view and view synchronization data.

2. Data is also unidirectional, which is called unidirectional data flow

Data is always transferred from the parent component to the child component, and the child component has no right (not recommended) to directly modify the data in the parent component.

3. Incompatible with IE8 and below browsers

The responsive principle utilizes the object.defineproperty of Es5, which does not support IE8


//Vue single page instance


    export default {
      data () {},
      methods: {},
      computed: {},
      watch: {}


Options options


Function to define the data of the page

data() {
    return {
        count: 2
        copyCount: 1

this.count // 2


Object, computing attributes, used to simplify complex logical processing

//The calculation attribute does not accept parameters and will cache dependent data. Return is required
    doubleCount: function () {
      return this.count *= 2

this.doubleCount // 4


Object that defines the function of the page

methods: {
    cLog(msg) {

This.clog ('function called ') // console output: function called


Object, attribute listening, used to listen for changes in certain data and make corresponding operations

watch: {
    count(value, [oldValue]) {
        //Value: changed value 
        this.copyCount = value + 1

//Automatically triggered when the count changes
this.count = 2
this.copyCount // 3


Object to register the component to the page

import UploadImg from 'xxxx'

components: { UploadImg }

// template

Basic grammar

Common instructions


Render HTML


Judge the syntax, control display / hide, and control whether to render dom


Control display / hide, similar to V-IF, but v-show is controlled through the display attribute


Two way data binding is generally used for forms, and the value attribute is bound by default


Abbreviation: Class

For dynamic attribute binding


Abbreviation @ Click

For event binding


Traversal syntax, support arrays, objects and strings

life cycle


Creating Vue objects


Data initialization. At this time, you can do some pre operations on the instance


El and data initialization


Mount el and data, and you can call the HTTP request


Before updating the DOM, the state can be further changed at this time without triggering the re rendering process


When updating the modified virtual DOM to the page, you should avoid changing the operation to avoid infinite cyclic update


Before the page is destroyed, you can do some reset operations, such as clearing the timer and DOM events


The page is destroyed. At this time, the Vue instance has been deleted and all operations are invalid

Route management Vue router

The official routing manager. It is deeply integrated with the core of vue.js, making it easy to build a single page application.

Routing configuration

//NPM Download
npm install vue-router
// router.js
import Vue from 'vue'
import VueRouter from 'vue-router'

//Define page routing (path, component)
export default new Router({
    {path: '/ foo', component: () = > Import ('/ pages / foo')}, // lazy loading of routing components
    { path: '/bar', component: '/pages/bar'}
// main.js
import router from './router.js'
new Vue({
  el: '#app',
  Router, // Mount routes to Vue instances
  render: h => h(App)

// page.vue

This. $router // access the router with built-in push and replace routing methods
This. $route // access the current route, with built-in route attributes such as path and query
// app.vue

Route jump

Declarative routing

Programmed routing

this.$router.push({ path: 'register', query: { plan: 'private' }})
This. $router. Replace (...) // different from push in that history records are not inserted
This. $router. Go ([number] n) // how many steps forward or backward in the history record

//When the routing parameters carry Chinese, it is recommended to use encodeurlcomponent transcoding first to avoid displaying garbled codes.

Routing guard

Navigation guard | Vue router official document

Global guard

Effective for all configured routes, but with low priority and internal routes.

Global front guard (common)

//Redirect to / login when user fails to authenticate
router.beforeEach((to, from, next) => {
  //To the routing object to be entered, from source routing, next hook function, release
  if ( !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()

Global resolution guard (understand)

router.beforeResolve((to, from, next) => {
  // ...

Global post hook (understand)

router.afterEach((to, from) => {
  //The routing guard does not accept the next hook function
  // ...
Route exclusive guard (understand)

This guard is only effective for configured routes. The method parameters of these guards are the same as those of the global front guard.

const router = new VueRouter({
  routes: [
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
Component internal guard (understand)

The following routing navigation guards can be defined directly in the routing component, which is only effective for the current component.

Beforerouteupdate (new in 2.2)

Guard in component | Vue router official document

Status manager vuex

to configure

// store.js
import Vue from 'vue'
import Vuex from 'vuex'


export default new Vuex.Store({
// main.js
import store from './store'

Vue.prototype.$store = store

Five core attributes


Data source, do not directly modify the state

// store.js
const state = {
    name: 'zzz'

//1. Direct call
this.$ // 'zzz'
//2. Auxiliary function mapping
computed: {
} // 'zzz'

The only way to change the state

const mutations = {
    updateName(state, newName) { = newName

//1. Direct call
this.$store.commit(updateName, 'zzh') // 'zzh'
//2. Auxiliary function mapping
methods: {
this.updateName('zzh') // 'zzh'

Store asynchronous operation and trigger mutation to change state asynchronously

const actions = {
    asyncUpdateName(context) {
        //Asynchronous operation, such as initiating an HTTP request to obtain the updated name, assuming name = XXX
        context.commit('updateName', // 'xxx'

//1. Direct call
//2. Auxiliary function mapping
methods: {

Data source processing, similar to calculating attributes

const getter = {
    formatName(state) {
        return + '2021'

//1. Direct call
this.$store.getter.formatName() // 'xxx2021'
//2. Auxiliary function mapping
computed: {
this.formatName() //  // 'xxx2021'

Modularization allows each module to manage its own set of state, changes, actions and getters.

//Inside the module
This. $store. State. Name // namespace is not required for internal access
//Module external
This. $store. State. Login. Name // login is the module namespace
Other properties are similar

Modules vuex official document


HTTP request Library Based on promise encapsulation, officially recommended

import axios from 'axios'

//Create and configure instances
    baseURL: ' ', // request reference address
    Timeout: 1000 // request timeout

//Request interceptor
axios.interceptors.request.use(request => {
    request.headers['Content-Type'] = 'application/json'
//Response interceptor
axios.interceptors.response.use(response => {
//Configuration request
export default {
    getId: () => axios.get('/getId'),
    getNameById: id =>'/getNameById', id)
import api from './api.js'

Vue.prototype.$api = api
this.$api.getId().then(res => {

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]