没有模板的组件 [英] Component without template
问题描述
我有一些代码可以对服务器进行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这样的文件中定义您的混入...
In a file like myCoolMixin.js define your mixin...
export default {
methods: {
myAwesomMethod() {
//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屋!