Vue - 重用方法的最佳方式 [英] Vue - best way to reuse methods

查看:36
本文介绍了Vue - 重用方法的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 vue 2 中 - 重用 vue 方法的正确做法是什么?

In vue 2 - what is correct practise for reusing vue methods?

与其在每个组件中都编写它们,不如将它们设为全局的最佳方法是什么?

Instead of writing them in each component, what is the best way to make them global?

推荐答案

Mixin

您可以为其创建一个mixin

Mixins 是一种为 Vue 组件分发可重用功能的灵活方式.mixin 对象可以包含任何组件选项.当组件使用 mixin 时,mixin 中的所有选项都会混合"到组件自己的选项中.

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be "mixed" into the component’s own options.

示例:

// define a mixin object
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}
// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"

如果不想在所有组件中手动混合,可以使用 global混入

If you dont want to mix it manually in all components, you can use global mixin

// inject a handler for `myOption` custom option
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

插件

另一种创建全局可用方法的方法是创建一个插件.

MyPlugin.install = function (Vue, options) {
  //  add global method or property
  Vue.myGlobalMethod = function () {
    // something logic ...
  }
  //  inject some component options
  Vue.mixin({
    created: function () {
      // something logic ...
    }
    ...
  })
  //  add an instance method
  Vue.prototype.$myMethod = function (options) {
    // something logic ...
  }
}

通过调用 Vue.use() 全局方法使用插件:

Use plugins by calling the Vue.use() global method:

Vue.use(MyPlugin)

现在这些方法将随处可用.您可以在此处查看此示例.

Now these methods will be available everywhere. You can see an example of this here.

这篇关于Vue - 重用方法的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆