没有模板的组件

问题描述 投票:0回答:2

我有一些代码可以对服务器进行 api 调用并返回一些 JSON。

它确实作为一种方法存在于我的组件中,但由于它有点长,我想将它提取到它自己的文件中

在 vuejs 中,这里的最佳实践是什么。

  • 应该是没有模板的组件吧?这将如何工作?

  • 我会只创建一个 es6 模块吗?

module vuejs2 components structure
2个回答
25
投票

我建议在这里使用mixin。

在像 myCoolMixin.js 这样的文件中定义你的 mixin ...

export default {
   methods: {
      myAwesomeMethod() {
         //do something cool...
      }
   }
}

你可以像组件一样在 mixin 中定义任何东西。例如数据对象、计算或监视的属性等。然后您只需将 mixin 包含在您的组件中。

import myCoolMixin from '../path/to/myCoolMixin.js'

export default {
   mixins: [myCoolMixin],
   data: function() {
      return: {
         //... 
      }
    },
    mounted: function() {
       this.myAwesomeMethod(); // Use your method like this!  
    }
 }

更多关于 Mixins 的信息:https://v2.vuejs.org/v2/guide/mixins.html


2
投票

Mixins 工作,或者你可以创建一个插件。这是文档示例:

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = function () {
    // something logic ...
  }

  // 2. add a global asset
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // something logic ...
    }
    ...
  })

  // 3. inject some component options
  Vue.mixin({
    created: function () {
      // something logic ...
    }
    ...
  })

  // 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // something logic ...
  }
}

Vue 插件

© www.soinside.com 2019 - 2024. All rights reserved.