vue的混入mixin

2019-04-18  本文已影响0人  lesdom

基础

当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
个人理解就是以另外一个独立的对象扩充组件

1、当组件和混入对象含有同名选项时,以组件数据优先。
2、混入对象的钩子将在组件自身钩子之前调用。

分类

局部(组件)

mixins - text.js

import api from '@/api/api' // 可以引用一些文件
let text = {
    methods: {
        say (text) {
            console.log(text)
        },       
    }
}
export default text

组件

import text from '@/mixins/text'
export default {
  mixins:[ text ],
}

全局

tool.js

import Vue from 'vue';
var tool = {
    methods: {
        say (text) {
            console.log(text)
        },       
    }
};
Vue.mixin(tool);

全局混入后在组件中使用this调用方法即可,如this.say('hello')

demo:Element-UI提示信息

utils - tool.js

import Vue from 'vue';

var tool = {
    methods: {
        showMsg(text) {
            return this.$message({
                showClose: true,
                message: text,
                type: 'warning'
            });
        },
        successMsg(text) {
            return this.$message({
                showClose: true,
                message: text,
                type: 'success'
            });
        },
        errorMsg(text) {
            return this.$message({
                showClose: true,
                message: text,
                type: 'error'
            });
        },
        confirm(text, callback) {
            this.$confirm(text, '提示', {
                type: 'warning'
            }).then(() => {
                callback();
            }).catch(error => console.log(error));
        }
    }
};

Vue.mixin(tool);

main.js

import './utils/tool.js';

文档

mixin

网站导航

网站导航

上一篇 下一篇

猜你喜欢

热点阅读