无模板的组件 [英] Component without template

查看:28
本文介绍了无模板的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bit of code that makes an api call to a server and returns some JSON.

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

It did exist as a method in my component but as it is getting a bit long I want to extract it to it's own file

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

In vuejs what is the best practice here.

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

  • should it be a component without a template? How would this work?

我会创建一个 es6 模块吗?

will I just create an es6 module?

推荐答案

我建议在这里使用 mixin.

I would suggest using a mixin here.

在 myCoolMixin.js 之类的文件中定义你的 mixin...

In a file like myCoolMixin.js define your mixin...

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

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

You can define anything in a mixin just like a component. e.g. data object, computed or watched properties, etc. Then you simply include the mixin in your component.

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://vuejs.org/v2/guide/mixins.html

More on Mixins here: https://vuejs.org/v2/guide/mixins.html

这篇关于无模板的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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