[Vuejs]-Vuex setting state

1👍

For reading the video state data, you can just use the mapState helper. For example, in your Video component

import { mapState } from 'vuex'

export default {
  name: 'Video',
  computed: mapState(['assetVideo'])
}

You can then reference this.assetVideo in your component’s methods and assetVideo in its template. This will be reactive to changes in the store.


For setting the value, you should (must) use a mutation. For example

const store = new Vuex.Store({
  strict: true, // always a good idea
  state: {
    assetVideo: {} // personally, I'd default to "null" but that's up to you
  },
  mutations: {
    setVideoAsset: (state, assetVideo) => (state.assetVideo = assetVideo)
  }
}

and in your components

methods: {
  selectVideo (video) {
    this.$store.commit('setVideoAsset', video)
  }
}

1👍

in your parent component:

// if you dont use namespace
import { mapMutations, mapState } from 'vuex'

export default {
  computed: {
    ...mapState(['assetVideo']),
    asset: {
      get() {
        return this.assetVideo
      },
      set(newValue) {
        this.setAssetVideo(newValue)
      }
    }
  },
  methods: {
    ...mapMutations(['setAssetVideo']),
  }
}

store

const store = {
  state: {
    assetVideo: {}
  },
  mutations: {
    setAssetVideo(state, payload) {
      state.assetVideo = payload
    }
  }
}

in your parent component you can change the state using this.asset = 'something' and it will change in store and anywhere else used

and also you can pass it to child components

Leave a comment