Babak Karimi Asl
Babak Karimi Asl

Reputation: 362

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 .

Upvotes: 0

Views: 642

Answers (1)

王仁宏
王仁宏

Reputation: 396

 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)
    }
  }
}

Upvotes: 1

Related Questions