在#NUXT.JS中存储常见组件方法的位置在哪里?

47

实际上我想知道在 #NUXT.JS 中存储常见组件方法的位置。

我尝试过的方法。 --> 在中间件中存储公共代码(毫无用处),因为据我所知,中间件只能处理对服务器的请求和响应。

methods: {

  // states methods.
  SwitchManager: function (__dataContainer, __key, __value) {
    // stand alone debugger for this module.
    let debug = __debug('computed:_3levelSwitch')
    // debug showing function loaded.
    debug('(h1:sizeCheck) creating switch..')
    // switch.
    switch (__key) {
      // fake allow set value to true of given key
      default:
        this[__dataContainer][__key][__value] = true
        break
    }
    return this[__dataContainer][__key][__value]
  },
  SizeCheck: function (__size) {
    // stand alone debugger for this module.
    let debug = __debug('tags:p')
    // debug showing function loaded.
    debug('(p:sizeCheck) checking..')
    // init switch.
    this.SwitchManager('pill', 'size', __size)
  },
  StateCheck: function (__state) {
    // stand alone debugger for this module.
    let debug = __debug('tags:h1')
    // debug showing function loaded.
    debug('(h1:sizeCheck) checking..')
    // init switch.
    this.SwitchManager('pill', 'state', __state)
  }
},
created () {
  // h1 tag size check
  this.SizeCheck(this.size)
  this.StateCheck(this.state)
}

1
我的回答有没有用?如果有什么不清楚的地方,请告诉我。 - Soleno
1个回答

117

我喜欢像使用普通vue.js一样去使用mixins。唯一的区别是对于全局 mixins,我会将它们包含在插件中,但首先:

非全局 mixins

我会为我的 mixins 创建一个额外文件夹。例如,在 /mixins/testMixin.js 中。

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

然后在布局、页面或组件中导入,通过 mixins 对象进行添加:

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

全局 mixin

例如在一个新文件 plugins/mixinCommonMethods.js 中:

import Vue from 'vue'

Vue.mixin({
  methods: {
    aCommonMethod () {}
  }
})

将该文件包含在nuxt.config.js中。

plugins: ['~/plugins/mixinCommonMethods']

之后,您可以在任何地方使用该方法,并使用this.commonMethod()调用它。但是根据vue.js文档的建议:

稀少而谨慎地使用全局混入,因为它影响到每个创建的Vue实例,包括第三方组件。在大多数情况下,您只应将其用于自定义选项处理,如上面的示例所示。将它们作为插件提供也是一个好主意,以避免重复应用。


注入$root和context

另一种可能性是在$root和context中进行注入


有没有什么办法可以在同一个mixin js文件中添加多个相关的mixin并可以分别导入? - Saba Ahang
2
在组件中,对于我来说失败了。"this.$globaFunction"不是一个函数。 - Marc
1
在插件/mixinCommonMethods.js中,您将如何导入NUXT的'context'对象作为全局mixin示例? - tomasz_kusmierczyk
请使用 this.$nuxt.globaFunction。 - Anees Hameed
@marc 和 @anees-hameed,如果你们想使用 this.$globalFunction,你需要先注入你的函数。请查看我在底部分享的链接。 - Soleno
请注意,Vue3中的mixins已被弃用: https://v3.vuejs.org/guide/mixins.html#drawbacks - kissu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接