1、概述
mixins
就是定義一部分公共的方法或者計算屬性,然后混入到各個組件中使用,方便管理與統一修改
2、示例
(1)定義一個mixin.js
export const mixinTest1 = { created() { this.hello(); }, methods: { hello() { console.log('mixinTest1'); } } };
(2)組件引入
import {mixinTest1} from './../assets/js/mixin'; export default { mixins:[mixinTest1], name: 'hello', data () { return { msg: 'Welcome to Your Vue.js App' } } }
這樣就可以直接調用到混入對象中的hello方法
3、第二個示例
<template>
</template>
<script> import Vue from 'vue'
var mixin = { created: function () { console.log(1) }, methods:{ hello(){ console.log('mixin:hello') } } } export default { data() { return { } }, methods: { hello(){ console.log('組件:hello') } }, created: function () { console.log(2) }, mixins: [mixin], mounted: function(){ this.hello(); } } </script>
輸出為:
created初始化了2次,並且組件自己的created后執行。
對於 methods, components 和 directives 將合並到同一個對象內。如果鍵沖突則組件的選項優先。