Component without template

旧时模样 提交于 2019-12-06 17:45:25

问题


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?


回答1:


I would suggest using a mixin here.

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

export default {
   methods: {
      myAwesomMethod() {
         //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




回答2:


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



来源:https://stackoverflow.com/questions/49870735/component-without-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!