How to set values from a child component (settings page) using vuex store in a Vue.js app?

廉价感情. 提交于 2020-07-15 09:25:28

问题


I'm trying to create a "settings" component which saves selected values into a store so that all the other components can use those values to change their appearance.

SettingsView.vue:

One of the settings (you can also see it on codepen):

[...]

<p>{{ themeColor }}</p>
<v-radio-group v-model="themeColor">
  <v-radio label="light" value="light"></v-radio>
  <v-radio label="dark" value="dark"></v-radio>
</v-radio-group>

[...]

<script>
export default {
  data () {
    return {
      // default value
      themeColor: 'light',
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.themeColor
    }
  },
  methods: {
    changeThemeColor() {
      this.$store.commit('changeThemeColor')
    },
  }
}
</script>

I don't know how to properly send the selected value of that setting to the store so I just created a mutation with a method (plus the need to have some default value, e.g. themeColor: 'light' like shown above, make it more confusing)

store/modules/Settings.js

const state = {
    themeColor: ''
  }
  
  const mutations = {
    changeThemeColor: state => {
      state.themeColor = ''
    }
  }
  
  export default {
    state,
    mutations
  }
  

How do I do this properly, so I can then use that value in all the components?

Do I have to use something like getters or actions? I don't really know.


回答1:


From https://vuex.vuejs.org/en/forms.html, I would use a computed property with getter and setter, ie

export default {
  computed: {
    themeColor: {
      get () {
        return this.$store.state.themeColor
      },
      set (value) {
        this.$store.commit('changeThemeColor', value)
      }          
    }
  }
}

Note, you do not need data or methods.


Your store should also look more like

const state = {
  themeColor: 'light' // default value
}

const mutations = {
  changeThemeColor (state, themeColor) {
    state.themeColor = themeColor
  }
}

Demo ~ https://codepen.io/anon/pen/YYbPww?editors=1011


For instances where you just want to display / read the themeColor state in your component, I recommend using the mapState helper.

import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState(['themeColor'])
}


来源:https://stackoverflow.com/questions/48412978/how-to-set-values-from-a-child-component-settings-page-using-vuex-store-in-a-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!