Fe-interview: [vue] 怎么给vue定义全局的方法?

Created on 2 Jul 2019  ·  9Comments  ·  Source: haizlin/fe-interview

[vue] 怎么给vue定义全局的方法?

vue

Most helpful comment

我知道的两种方式:

  • 第一种:挂载到Vue的prototype上。把全局方法写到一个文件里面,然后for循环挂载到Vue的prototype上,缺点是调用这个方法的时候没有提示
 Object.keys(tools).forEach(key => {
      Vue.prototype[key] = tools[key]
 })
  • 第二种:利用全局混入mixin,因为mixin里面的methods会和创建的每个单文件组件合并。这样做的优点是调用这个方法的时候有提示
Vue.mixin(mixin)
new Vue({
    store,
    router,
    render: h => h(App),
}).$mount('#app')

import tools from "./tools"
import filters from "./filters"
import Config from '../config'
import CONSTANT from './const_var'

export default {
    data() {
        return {
            CONFIG: Config,
            CONSTANT: CONSTANT
        }
    },
    methods: {
        // //将tools里面的方法挂载到vue上,以方便调用,直接this.$xxx方法名就可以了
        // Object.keys(tools).forEach(key => {
        //     Vue.prototype[key] = tools[key]
        // })
        //将tools里面的方法用对象展开符混入到mixin上,以方便调用,直接this.$xxx方法名就可以了
        ...tools
    },
    filters: {
        // //将filter里面的方法添加了vue的筛选器上
        // Object.keys(filters).forEach(key => {
        //     Vue.filter(key, filters[key])
        // })
        ...filters
    }
}

All 9 comments

我知道的两种方式:

  • 第一种:挂载到Vue的prototype上。把全局方法写到一个文件里面,然后for循环挂载到Vue的prototype上,缺点是调用这个方法的时候没有提示
 Object.keys(tools).forEach(key => {
      Vue.prototype[key] = tools[key]
 })
  • 第二种:利用全局混入mixin,因为mixin里面的methods会和创建的每个单文件组件合并。这样做的优点是调用这个方法的时候有提示
Vue.mixin(mixin)
new Vue({
    store,
    router,
    render: h => h(App),
}).$mount('#app')

import tools from "./tools"
import filters from "./filters"
import Config from '../config'
import CONSTANT from './const_var'

export default {
    data() {
        return {
            CONFIG: Config,
            CONSTANT: CONSTANT
        }
    },
    methods: {
        // //将tools里面的方法挂载到vue上,以方便调用,直接this.$xxx方法名就可以了
        // Object.keys(tools).forEach(key => {
        //     Vue.prototype[key] = tools[key]
        // })
        //将tools里面的方法用对象展开符混入到mixin上,以方便调用,直接this.$xxx方法名就可以了
        ...tools
    },
    filters: {
        // //将filter里面的方法添加了vue的筛选器上
        // Object.keys(filters).forEach(key => {
        //     Vue.filter(key, filters[key])
        // })
        ...filters
    }
}

我知道一种方法,就是在任意vue文件中写全局函数

// 创建全局方法
this.$root.$on('test', function(){
    console.log('test');
})

// 销毁全局方法
this.$root.$off('test');

// 调用全局方法
this.$root.$emit('test');

prototype

1、通过prototype,这个非常方便。Vue.prototype[method]=method;
2、通过插件Vue.use(plugin);
3、通过mixin,Vue.mixin(mixins);

1.挂载到prototype上,上面说得vue.use的实现没有挂载的功能,只是触发了插件的install方法,本质还是使用了vue.prototype。
2.vue.mixin

方法一:给vue原型加方法:vue.protype.get=function(){}

1.挂载在prototype上,Vue.prototype
2.Vue.mixin

  1. Vue.prototype.xxx
  2. Vue.mixin,在某个钩子函数里面可以拿到vue实例

Vue.prototype Vue.mixin

Was this page helpful?
0 / 5 - 0 ratings