如何在 Vue.js 应用程序中使用 vuex 存储从子组件(设置页面)设置值? [英] How to set values from a child component (settings page) using vuex store in a Vue.js app?
问题描述
我正在尝试创建一个设置"将选定值保存到存储中的组件,以便所有其他组件可以使用这些值来更改其外观.
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.
其中一项设置(您也可以在 on codepen 上查看):
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>
我不知道如何正确地将该设置的选定值发送到商店,所以我只是用一个方法创建了一个突变(加上需要有一些默认值,例如 themeColor: 'light'
如上所示,让它更混乱)
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)
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?
我是否必须使用诸如 getters
或 actions
之类的东西?我真的不知道.
Do I have to use something like getters
or actions
? I don't really know.
推荐答案
来自 https://vuex.vuejs.org/en/forms.html,我会使用带有 getter 和 setter 的计算属性,即
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)
}
}
}
}
注意,您不需要 data
或 methods
.
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
}
}
<小时>
演示 ~ https://codepen.io/anon/pen/YYbPww?editors=1011
如果您只想显示/读取组件中的 themeColor
状态,我建议使用 mapState
助手.
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'])
}
这篇关于如何在 Vue.js 应用程序中使用 vuex 存储从子组件(设置页面)设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!