Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...