Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - Nuxt 2 - the need to access 'this' when constructing computed ( for a zero import approach )

i tried these:

of course the following will not work:

    computed:{
       amount : this.$myPlugin.syncStore('orders/amount') // using Nuxt plugin but "this" is undefined here
    }

also computed as a function does not work:

   computed(){
       return {
          amount : this.$myPlugin.syncStore('orders/amount')
       }
   }
/*
[Vue warn]: Invalid value for option "computed": expected an Object, but got Function.
*/

another way is importing something: ( which is ugly )

import { syncStore } from '@/utils'  // importing in .vue is ugly
...
computed:{
    amount : syncStore('orders/amount') 
}

and i want a zero import approach . thanks to Nuxt plugins ,any helper code can be putted and accessed from this.

the only working code that i found is this jsfiddle link, i copy a slightly modified code here:

...
  beforeCreate() {
    if(!this.$options.computed)  this.$options.computed = {}

    this.$options.computed['amount'] = this.$myPlugins.syncStore('store1/amount')
  }
...

but it is a hack .

is there other ways ? thank you .

question from:https://stackoverflow.com/questions/65916232/nuxt-2-the-need-to-access-this-when-constructing-computed-for-a-zero-impor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 computed:{
       amount : this.$myPlugin.syncStore('orders/amount') // using Nuxt plugin but "this" is undefined here
    }

are you looking for this?

computed: {
  amount () {
    return this.$myPlugin.syncStore('orders/amount')
  }
}

---- update use set and get in computed

this is in vue doc

computed: {
  amount: {
    get () {
      return this.$myPlugin.syncStore('orders/amount')
    },
    set (val) {
      this.$myPlugin.methodToStore(val)
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...