简体   繁体   中英

vue.js: When implementing the "Simple State Management from Scratch" approach, how to pass on/access the store?

This may be a really dumb question, but after reading the state management documentation of vue.js, i'd like to play around with the store pattern.

I noticed that the store.state is shared among the two apps in the example. But how would i now call the setMessageAction method of the store from within a component? Shouldn't the store be somehow injected into/registered with the vue instance in order to be accessible via this from within a component or something like that?

Yes, you are correct.

You should declare your store in your component declaration as described here

document.js


var store = {
    debug: true,
    state: {
          message: 'Hello!'
         },
    setMessageAction (newValue) {
        if (this.debug) console.log('setMessageAction triggered with', newValue)
        this.state.message = newValue
    },

    clearMessageAction () {
        if (this.debug) console.log('clearMessageAction triggered')
        this.state.message = ''
    }
 }



var vmA = new Vue({
   data: {
    privateState: {},

    <!-- HERE YOU ARE PASSING THE STATE -->
    sharedState: store.state
    }
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM