Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day169:怎么给 Vue 定义全局方法 #983

Open
Genzhen opened this issue Nov 2, 2020 · 1 comment
Open

Day169:怎么给 Vue 定义全局方法 #983

Genzhen opened this issue Nov 2, 2020 · 1 comment
Labels
Vue teach_tag

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Nov 2, 2020

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

@Genzhen Genzhen added the Vue teach_tag label Nov 2, 2020
@luuman
Copy link

luuman commented Nov 2, 2021

通过prototype,这个非常方便。Vue.prototype[method]=method

挂载到Vue的prototype上。把全局方法写到一个文件里面,然后for循环挂载到Vue的prototype上,缺点是调用这个方法的时候没有提示

 Object.keys(tools).forEach(key => {
      Vue.prototype[key] = tools[key]
 })

通过mixin,Vue.mixin(mixins)

利用全局混入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.use(plugin)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Vue teach_tag
Projects
None yet
Development

No branches or pull requests

2 participants