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
In vuejs what is the best practice here.
should it be a component without a template? How would this work?
will I just create an es6 module?
A template is a form of HTML that tells Angular how to render the component.
As you can see, in this view's @Component() meta-data, there is no "selector" property. With routable components, this isn't required. But, it can be used.
When we define the template in an external file and then after we link with our component is said to be an external template. In other words, The External templates define the HTML code in a separate file and we can refer to that file using templateURL property of Component decorator.
Note Although it's possible for a component to render multiple templates, we recommend using an if:true|false directive to render nested templates conditionally instead. Create multiple HTML files in the component bundle.
I would suggest using a mixin here.
In a file like myCoolMixin.js define your mixin...
export default { methods: { myAwesomeMethod() { //do something cool... } } }
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! } }
More on Mixins here: https://vuejs.org/v2/guide/mixins.html
Mixins work, or you could create a plugin. Here's the docs example:
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 Plugins
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With