Vue Life Cycle (8)

Each lifecycle is created() Mounted () updated() destroy() keep-alive (LRU algorithm) activated deactivated

include/exclude

Parent component listens to child component Mounted

child

Echo () {this.$emit(" echo ")}Copy the code

parent

The child @ hook: mounted = "dosomething" > child > <Copy the code

js

vm.$on('hooks:created', cb) ;
Copy the code

Parent-child component lifecycle order

  • Parent beforeCreate created beforeMount child beforeCreate created beforeMount Mounted Parent Mounted
  • Child update parent beforeUpdate Child beforeUpdate Updated Parent updated
  • Destroy parent beforeDestory child beforeDestory Destroyed parent destroyed

Vue component communication (One-way data flow)

props on/on/on/emit ref.child.data/.method()vuexref.child.data / .method() vuex ref.child.data/.method()vuexparent $Children eventBus cross-component provide Inject Plug-in Parent for child consumption

Vue common Logic Extraction (vue.mixin)

MergeOptions (Data, life cycle, etc.)

  • global
    Vue.mixin(mixin)
    Copy the code
  • local
    import mixin from'... 'export default {
        mixins: [mixin],
        data () { return{}}}Copy the code

If multiple components reference the same mixin, the mixin is independent and does not affect each other. When calling a mixin, the component overwrites the mixin

Asynchronous components (Vue2.0 must be functions)

components: {
    AddComp: (resolve) = > import('.. /components/Confirm.vue')}Copy the code

Dynamic components

<component :is="settingTabs[currentTab].component"></component>
currentTab: 0.settingTabs: [{ title: 'Basic Settings'.component: 'basic-setting' }]
Copy the code

slot

  • Slot: scoped to the parent my-component
    <modal>
        <slot name="content"></slot>
    </modal>
    Copy the code

    The parent component calls my-Component

    <ConfirmEle>
        <template #contentorslot="Content"></template>
    </ConfirmEle>
    Copy the code
  • Slot-scope scope child component

Computed Watch Method difference

  • Methods M: c, W are based on watcher implementation of c: cache, depending on changes to update the view
  • Monitor W: 1, 2

Vuex

  • Basic properties
import Vuex from 'vuex';
Vue.use(Vuex);
new Vuex.Store({
    state: {
        name: ‘’
    },
    mutations: {
        setName (state, name) {
            state.name = name
        }
    },
    actions: {
        login({ commit }, res) {
            commit('setName', res.data.name);
            localStorage.setItem('userName', res.data.name)
            // axios.defaults.headers.common.Authorization = token;
        },
        logout({ commit }) {
            return new Promise((resolve) = > {
                localStorage.clear();
                sessionStorage.clear();
                // axios.defaults.headers.common.Authorization = '';resolve(); }); }},modules: {
        user,
        setting
    }
})
Copy the code
  • Vuex reference
computed: { ... mapState('module1'['state1'.'state2'])},methods: {
    ...mapMutations('module2'['mutations1'.'mutations2']),}this.$store.dispatch('user/login', res).then(() = > {
    this.$router.push({ name: 'workSpace' });
});
this.$stroe.commit()
computed: {
    audioStatus: {
        get () {
            return this.$store.state.setting.audioStatus;
        },
        set (val) {
            this.$store.state.setting.audioStatus = val; }}}Copy the code

Custom instruction

Bind inserted Update Global hook function

Vue.directive('image-preview'.function (el, binding, vnode) {})
Copy the code

local

export defaults {
    directives: {
        focus: {
            inserted: function (el) { el.focus() }
        }
    }
}
Vue.directive('has', {
    // When the bound element is inserted into the DOM
    inserted: function(el, binding) {
        var role = store.state.user.role
        if(! role)return false
        let auth = role.some(e= > {
            return e.id === 1
        })
        !auth ? el.style.display = 'none' : el.style.display = 'inline-block'}})Copy the code

Vue bidirectional binding principle (responsive)

Data hijacking + published-subscribe recursively traverses the entire data, object.defineProperty () hijacks setter and getter methods for individual properties; Add subscriber to subscription center when data get, notify subscription center when data set, rely on collection Watcher, later dep.notify notify Watcher, asynchronous render update)

  1. initData()
  2. Observer (listener, hijack and listen)
  3. Dep rely on
  4. The Watcher subscriber
  5. Compile Compile
vue-template-complier // Parse the template into vue browser syntax
VueTemplateComplier.compile(` < div v - if = "true" > < / div > `) 'with(this){
	return} 'Copy the code

Data uses factory functions

New Vue({data:{}}) new Vue() only once, create a root instance data: {} data() {return {}} data() => (return obj: {name: VueComponent: VueComponent: VueComponent: VueComponent: VueComponent: VueComponent: VueComponent: VueComponent: VueComponent: VueComponent ‘123’}) references vc.$options.data()

var Component1 = function() {
    this.data = this.data()
}
Component1.prototype.data = function() {
    return {
        a: 1.b: 2}}var Component2 = function() {
    this.data = this.data()
}
Component2.prototype.data = () = > {
    return {
        a: 1.b: 2}}var Component3 = function() {}
Component3.prototype.data = {
    a: 1.b: 2
}

var c1 = new Component1()
var c2 = new Component2()
var c3 = new Component3()

// Change the component
component1.data.b = 3
component2.data.b / / 2
Copy the code

Vue uses asynchronous rendering

Update view nextTick asynchronously (clear watcher queue)

nextTick()

Ensure that the current view rendering is complete (update icon echarts) nextTick(asynchronous updates to the system, call $nextTick directly) put all these updates into callback=[] array and then asynchronous microtask TimerFunc =(Promise.resolve().then(callback))

Vue template Compilation (Parse, Optimize, Generate)

Render (_c()); render (_c()); render (_c()); render (_c()); render (_c()); render (_c());

  • Vue instance render weights
    let vue = new Vue({
        el: '#app'.data() {
            return {
                a: 1.b: [1]}},render(h) {
            return h('div', { id: 'hhh' }, 'hello')},template: `
            `
    }).$mount('#app')
    console.log(vue)
    
    // Render the root node
    $mount(); $mount();
    
    // Render the template
    // render takes precedence
    // Have template: parse, call render
    // None template: Parses the outerHTML of the el root node and calls render
    Copy the code
  • The component rendering

    Build the child component constructor with vue.extend ()

    Instantiate when a child component is called,$mount()Mount components tovm.$elOn, add the child component to watcher
    Vue.use(MyPlugin)
    MyPlugin.install = function (Vue, options) {
      // 1. Add a global method or attribute
      Vue.myGlobalMethod = function () {}
    
      // 2. Add global resources
      Vue.directive('my-directive', {
        bind (el, binding, vnode, oldVnode) {}
      })
    
      // 3. Inject component options
      Vue.mixin({
        created: function () {}})// 4. Add instance methods
      Vue.prototype.$myMethod = function (methodOptions) {}}var MyCompontent = Vue.extend({template: '< div > < / div >'}) Vue.com ponent (' my - component, MyCompontent)newMyCompontent () $mount (' # ') app /new MyCompontent({el: "# app"})Copy the code
  • There can only be one root node under the template (diff algorithm only allows one · root node). PatchVnode () diff compares its sibling first and then its child nodes to determine whether there are any child nodes to compare

Git front-end commit specification

Commitizen (vue+commitlint+husky) NPM install –save-dev “@commitlint/cli”: “^8.2.0” “@commitlint/config-conventional”: “^8.2.0” NPM install husky –save-dev Create commitlint.config.js

Which fields are returned by the back-end file stream

header: {},

data: {},

config: {}