Where to store common component methods in #NUXT.JS

前端 未结 1 649
忘掉有多难
忘掉有多难 2021-01-31 08:20

Actually i want to know where to store common components methods in #NUXT.JS.

things which i have tried. --> Storing common code in middleware (its use-less) because ac

相关标签:
1条回答
  • 2021-01-31 08:54

    I go for mixins like with plain vue.js. Only difference - for global mixins - I include them as a plugin, but first:

    Non global mixins

    I would create an extra folder for my mixins. For example in a /mixins/testMixin.js

    export default {
      methods: {
        aCommonMethod () {}
      }
    }
    

    Then import in a layout, page or component and add it via the mixins object:

    <script>
      import commonMixin from '~/mixins/testMixin.js
      export default {
        mixins: [commonMixin]
      }
    </script>
    


    Global mixins

    For example in a new file plugins/mixinCommonMethods.js:

    import Vue from 'vue'
    
    Vue.mixin({
      methods: {
        aCommonMethod () {}
      }
    })
    

    Include that file then in nuxt.config.js

    plugins: ['~/plugins/mixinCommonMethods']
    

    After that you would have the method everywhere available and call it there with this.commonMethod(). But here an advice from the vue.js docs:

    Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components. In most cases, you should only use it for custom option handling like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate application.


    Inject in $root & context

    Another possibility would be to Inject in $root & context

    0 讨论(0)
提交回复
热议问题