Vue 2.0 Foundation

Time:2021-11-23

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

characteristic

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


example

//Vue single page instance

    label...


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


    Style

Options options

data

Function to define the data of the page

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

//Use
this.count // 2

computed

Object, computing attributes, used to simplify complex logical processing

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

//Use
this.doubleCount // 4

methods

Object that defines the function of the page

methods: {
    cLog(msg) {
        console.log(msg)
    }
}

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

watch

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

components

Object to register the component to the page

import UploadImg from 'xxxx'

components: { UploadImg }

// template

Basic grammar

Common instructions

v-html

Render HTML

v-if

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

v-show

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

v-model

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

v-bind

Abbreviation: Class

For dynamic attribute binding

v-on

Abbreviation @ Click

For event binding

v-for

Traversal syntax, support arrays, objects and strings

life cycle

beforeCreated

Creating Vue objects

created

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

beforeMounted

El and data initialization

mounted

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

beforeUpdated

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

updated

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

beforeDestory

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

destoryed

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'
Vue.use(VueRouter)

//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 (to.name !== '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.

beforeRouteEnter
Beforerouteupdate (new in 2.2)
beforeRouteLeave

Guard in component | Vue router official document


Status manager vuex

to configure

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

Vue.use(Vuex)
...

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules
})
// main.js
import store from './store'

Vue.prototype.$store = store

Five core attributes

state

Data source, do not directly modify the state

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


//1. Direct call
this.$store.state.name // 'zzz'
//2. Auxiliary function mapping
computed: {
    ...mapState(['name'])
}
this.name // 'zzz'
mutations

The only way to change the state

const mutations = {
    updateName(state, newName) {
        state.name = newName
    }
}


//1. Direct call
this.$store.commit(updateName, 'zzh') // state.name: 'zzh'
//2. Auxiliary function mapping
methods: {
    ...mapMutations(['updateName'])
}
this.updateName('zzh') // state.name: 'zzh'
actions

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', res.name) // state.name: 'xxx'
    }
}


//1. Direct call
this.$store.dispatch(asyncUpdateName)
//2. Auxiliary function mapping
methods: {
    ...mapActions(['asyncUpdateName'])
}
this.asyncUpdateName()
getters

Data source processing, similar to calculating attributes

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


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

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


Axios

HTTP request Library Based on promise encapsulation, officially recommended

import axios from 'axios'

//Create and configure instances
axios.create({
    baseURL: ' http://www.baidu.com ', // 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 => {
    ...
    return response.data
})
//Configuration request
export default {
    getId: () => axios.get('/getId'),
    getNameById: id => axios.post('/getNameById', id)
}
import api from './api.js'

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

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 […]