我正在尝试创建一个“设置”组件,它将选定的值保存到存储中,以便所有其他组件都可以使用这些值来更改其外观。
设置视图.vue:
其中一项设置(你也可以看到在代码笔上):
[...]
<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'
如上所示,使其更加混乱)
商店/模块/Settings.js
const state = {
themeColor: ''
}
const mutations = {
changeThemeColor: state => {
state.themeColor = ''
}
}
export default {
state,
mutations
}
如何正确执行此操作,以便我可以在所有组件中使用该值?
我必须使用类似的东西吗getters
or actions
?我真的不知道。
From https://vuex.vuejs.org/en/forms.html,我将使用带有 getter 和 setter 的计算属性,即
export default {
computed: {
themeColor: {
get () {
return this.$store.state.themeColor
},
set (value) {
this.$store.commit('changeThemeColor', value)
}
}
}
}
请注意,您不需要data
or methods
.
您的商店也应该看起来更像
const state = {
themeColor: 'light' // default value
}
const mutations = {
changeThemeColor (state, themeColor) {
state.themeColor = themeColor
}
}
Demo ~ https://codepen.io/anon/pen/YYbPww?editors=1011
对于您只想显示/读取的实例themeColor
在你的组件中声明,我建议使用mapState helper.
import { mapState } from 'vuex'
export default {
// ...
computed: mapState(['themeColor'])
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)