没有模板的组件
Component without template
我有一些代码可以 api 调用服务器和 returns 一些 JSON。
它确实作为方法存在于我的组件中,但由于它有点长,我想将它提取到它自己的文件中
在 vuejs 中,这里的最佳实践是什么。
应该是没有模板的组件吧?这将如何运作?
我会只创建一个 es6 模块吗?
我建议在这里使用 mixin。
在类似 myCoolMixin.js 的文件中定义您的混入...
export default {
methods: {
myAwesomeMethod() {
//do something cool...
}
}
}
您可以像定义组件一样在 mixin 中定义任何内容。例如数据对象、计算或监视属性等。然后您只需在组件中包含混入即可。
import myCoolMixin from '../path/to/myCoolMixin.js'
export default {
mixins: [myCoolMixin],
data: function() {
return: {
//...
}
},
mounted: function() {
this.myAwesomeMethod(); // Use your method like this!
}
}
更多关于 Mixin 的信息:https://vuejs.org/v2/guide/mixins.html
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 ...
}
}
我有一些代码可以 api 调用服务器和 returns 一些 JSON。
它确实作为方法存在于我的组件中,但由于它有点长,我想将它提取到它自己的文件中
在 vuejs 中,这里的最佳实践是什么。
应该是没有模板的组件吧?这将如何运作?
我会只创建一个 es6 模块吗?
我建议在这里使用 mixin。
在类似 myCoolMixin.js 的文件中定义您的混入...
export default {
methods: {
myAwesomeMethod() {
//do something cool...
}
}
}
您可以像定义组件一样在 mixin 中定义任何内容。例如数据对象、计算或监视属性等。然后您只需在组件中包含混入即可。
import myCoolMixin from '../path/to/myCoolMixin.js'
export default {
mixins: [myCoolMixin],
data: function() {
return: {
//...
}
},
mounted: function() {
this.myAwesomeMethod(); // Use your method like this!
}
}
更多关于 Mixin 的信息:https://vuejs.org/v2/guide/mixins.html
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 ...
}
}