【问题标题】:Where to store common component methods in #NUXT.JS#NUXT.JS 中常用组件方法的存储位置
【发布时间】:2018-06-13 19:14:38
【问题描述】:

其实我想知道#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)
}

【问题讨论】:

  • 我的回答有用吗?如果有任何不清楚的地方,请告诉我。

标签: javascript vue.js nuxt.js


【解决方案1】:

我喜欢mixins,就像普通的 vue.js 一样。唯一的区别 - 对于全局混合 - 我将它们作为插件包含,但首先:

非全局混入

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

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

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

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


全局混入

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

import Vue from 'vue'

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

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

plugins: ['~/plugins/mixinCommonMethods']

之后,您将在任何地方都可以使用该方法,并使用this.commonMethod() 在那里调用它。但这里有来自vue.js docs 的建议:

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


在 $root 和上下文中注入

另一种可能是Inject in $root & context

【讨论】:

  • 知道如何在同一个 mixin js 文件中添加多个可以单独导入的相关 mixin 吗?
  • 对我来说失败了。 "this.$globaFunction" 不是组件中的函数。
  • 如何在示例性的全局​​ mixin 中导入 NUXT 'context' 对象:plugins/mixinCommonMethods.js ?
  • 使用 this.$nuxt.globaFunction
  • @marc 和 @anees-hameed 使用 this.$globalFunction 你需要先注入你的函数。请参阅我在底部分享的链接。
猜你喜欢
  • 2021-11-06
  • 2019-06-21
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多