應用三:Vue之混入(mixin)與全局混入

 

(注:本文適用於有必定Vue基礎或開發經驗的讀者,文章就知識點的講解不必定全面,但倒是開發過程當中很實用的)vue

 

首先介紹一下混入mixin的概念:app

 

官方文檔:混入提供了一種很是靈活的方式,來分發 Vue 組件中的可複用功能。一個混入對象能夠包含任意組件選項。當組件使用混入對象時,全部混入對象的選項將被「混合」進入該組件自己的選項。模塊化

 

我的理解:混入就是用來對vue組件中的公共部分,包括數據對象、鉤子函數、方法等全部選項,進行提取封裝,以達到代碼的複用。函數

 

接下來經過一個簡單的例子看看混入的基礎用法:this

首先新建一個mixin.js文件,添加如下代碼。spa

let mixin = {
  data() {
    return {
      msg: 'hello mixin'
    }
  },
  created() {
    console.log('混入的鉤子函數');
  },
  methods: {
    show() {
      console.log(this.msg);
    }
  }
}
export default mixin;

 

而後新建一個index.vue文件,添加如下代碼。eslint

<template>
  <div id="myVue">
    <span @click="show">{{msg}}</span>
  </div>
</template>
<script>
  import myMixin from './mixin.js';
  export default {
    name: 'myVue',
    mixins: [myMixin],
    created() {
      console.log('組件自身的鉤子函數');
    }
  }
</script>

 

注意:在index.vue文件中要先引入mixin.js文件,而後就能夠直接使用mixin.js中定義的數據msg和方法show。code

 

而對於混入對象以及組件自身的created鉤子函數呢,它們都將被調用。但混入對象的鉤子會在組件自身的鉤子以前調用。component

若是組件自身定義了與鉤子對象中同名的數據或方法,爲了不衝突,vue將優先使用組件自身的數據或方法。對象

 

固然也能夠將混入對象全局註冊,在以後新建的全部vue組件中就均可以使用。

接下來分享一下全局混入的註冊方法。

 

方法一:在工程的main.js中直接註冊,實現以下:

import Vue from 'vue';
import App from './App';

Vue.mixin({
  created() {
    console.log('全局混入的鉤子函數');
  }
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
});

 

方法二:模塊化註冊,新建mixin.js文件並添加如下代碼:

export default {
  install(Vue) {
    Vue.mixin({
      created() {
        console.log('全局混入的鉤子函數');
      }
    })
  }
}

 

而後在main.js中引入該文件並使用use方法進行註冊

import Vue from 'vue';
import App from './App';
import myMixin from './mixin.js';

Vue.use(myMixin);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
});
相關文章
相關標籤/搜索