您尝试做的可能没有特别简单的解决方案,而我将如何做到这一点是使用组件在加载时设置的存储状态元素。该组件将在存储中提交一个更改状态元素的突变。然后布局将通过 getter 使用该状态元素来设置图像 url。这是我如何编码的。在存储状态中,我有一个类名数组,我们称之为“headState”,以及一个将被分配其中一个类名的元素,称为“headStateSelect:
//store/index.js
state: {
headState: ['blue', 'red', 'green'],
headStateSelect : ''
}
在您的组件中,您可以使用 fetch 或 async fetch 提交一个突变,该突变将使用“headState”元素之一设置“headStateSelect”。
//yourComponent.vue
async fetch ({ store, params }) {
await store.commit('SET_HEAD', 1) //the second parameter is to specify the array position of the 'headState' class you want
}
并存储:
//store/index.js
mutations: {
SET_HEAD (state, data) {
state.headStateSelect = state.headState[data]
}
}
在商店中,我们还应该有一个返回“headStateSelect”的getter,以便我们的布局可以轻松获取它。
getters: {
head(state) {
return state.headStateSelect
}
}
最后,在布局中,我们可以使用计算属性来获取我们的 getter:
//layouts/default.vue
computed: {
headElement() {
return this.$store.getters.head
}
}
并且布局可以使用计算属性来设置一个类,如下所示:
//layouts/default.vue
<template>
<div :class="headElement">
</div>
</template>
现在,布局中的 div 将设置为类名“red”(即 store.state.headState[1]),您可以在布局文件中使用 .red css 类来设置您想要的样式,包括背景图片。