Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Component without template

Tags:

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?

like image 986
LeBlaireau Avatar asked Apr 17 '18 05:04

LeBlaireau


People also ask

What is a template component?

A template is a form of HTML that tells Angular how to render the component.

Can we create component without selector?

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.

What is the difference between template and templateUrl in component parameters?

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.

Can a component have multiple templates?

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.


2 Answers

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

like image 187
skribe Avatar answered Sep 17 '22 19:09

skribe


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

like image 35
Brian Lee Avatar answered Sep 17 '22 19:09

Brian Lee