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

怎么给vue定义全局的方法?,第1张

怎么给vue定义全局的方法

我知道的两种方式:

  • 第一种:挂载到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    }}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4895968.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存