【问题标题】:Vuex setting stateVuex设置状态
【发布时间】:2020-11-24 00:28:08
【问题描述】:

我有一个要绑定到子组件的道具。我正在尝试摆脱这个并将值设置为 vuex 全局状态中的数据。

<VideoPip :asset="asset" v-show="pipEnabled === true" />

如何设置 this.$store.state.assetVideo; 默认为等于资产值的空对象?我会在计算属性中这样做吗?

【问题讨论】:

  • 如果您不打算更改子组件中asset prop 的值,请使用计算属性或使用mapState
  • asset 是一个根据用户点击的视频而变化的对象
  • 如果更改发生在存储突变无关紧要
  • 所以我可以有一个计算属性来设置 this.$state.store.assetVideo = this.asset?
  • 直接改变状态不是不好的做法吗?

标签: javascript vue.js state vuex


【解决方案1】:

在你的父组件中:

// 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']),
  }
}

商店

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

在您的父组件中,您可以使用 this.asset = 'something' 更改状态,它会在商店和其他任何使用的地方发生变化

你也可以将它传递给子组件

【讨论】:

    【解决方案2】:

    要读取视频状态数据,您可以使用mapState helper。例如,在您的 Video 组件中

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

    然后您可以在组件的方法中引用 this.assetVideo 并在其模板中引用 assetVideo。这将对商店的变化做出反应。


    要设置值,您应该(必须)使用突变。例如

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

    在你的组件中

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

    【讨论】:

    • 你打败了我,基本上我们有相同的想法,但我倾向于使用计算设置器
    • @Talal 我不确定 OP 是否试图改变他们的 Video 组件或其他地方的值。我假设后者
    • OP 说它会在聊天的父组件中发生变异,但问题中的重要问题以正确的方式回答,你就搞定了
    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2022-01-05
    • 2018-07-04
    相关资源
    最近更新 更多