【发布时间】:2020-12-01 07:14:45
【问题描述】:
我有一个在 Vue 中构建的电子商务应用程序 (SPA),下面是商店的快照
state: {
cart: [],
totalItems: {
count: 0
}
},
getters: {
totalItems(){
if(window.localStorage.totalItems){
return JSON.parse(window.localStorage.totalItems)
}
else{
let totalItems = { count: 0}
return totalItems
}
}
},
mutations: {
setCart(state, cart){
state.cart = cart
window.localStorage.cart = JSON.stringify(cart)
},
setTotalItems(state, totalItems){
state.totalItems = totalItems
window.localStorage.totalItems = JSON.stringify(totalItems)
}
},
actions: {
addToCart({ commit, getters }, productId){
let cart = getters.cart
let totalItems = getters.totalItems
if(cart.length == 0){
cart.push({id: productId, quantity: 1})
totalItems.count++
}
else if(cart.find(({ id }) => id == productId)){
let item = cart.find(({ id }) => id == productId)
item.quantity++
totalItems.count++
}
else{
cart.push({id: productId, quantity: 1})
totalItems.count++
}
commit('setCart', cart)
commit('setTotalItems', totalItems)
},
setTotalItems({ commit }, totalItems){
commit('setTotalItems', totalItems)
}
}
在我的 App.vue 文件下面 -
<template>
<v-app>
<v-app-bar
app
color="red"
dark
>
<v-btn text to="/">Vue Shop</v-btn>
<v-spacer></v-spacer>
<v-btn text to="/cart">
<v-badge v-if="totalItems.count" :content="totalItems.count"><v-icon>mdi-cart</v-icon></v-badge>
</v-btn>
</v-app-bar>
<v-main>
<router-view></router-view>
</v-main>
</v-app>
</template>
<script>
export default {
name: 'App',
components: {
},
computed: {
totalItems(){
return this.$store.getters.totalItems
}
}
};
</script>
当我加载网站时,我可以看到计算的属性正在计算。但是,当我单击下面显示的 Home.vue 文件上的“添加到”按钮时,它应该是
- 调用 addToCart 方法
- 依次从商店分派 addToCart 操作
- 我在哪里计算 totalItems 并使用 setTotalItems 突变设置值
我面临的问题是,当我单击“添加到”按钮时,我可以看到 localStorage 中的 totalItems 的值已更新,但它没有反映在 v-app-bar 组件中。仅当我导航到其他页面然后返回主页时才会这样做。
当我通过将值存储在 state 而不是 localStorage 来实现时,它会正确反映,而无需导航到其他页面。
有没有办法在仍然使用 localStorage 而不是 store 的情况下实现这一点
<template>
<v-container>
<v-row>
<v-col v-for="product in products" :key="product.id">
<v-card width="300" height="300">
<v-img :src=product.imgUrl width="300" height="200"></v-img>
<v-card-title>
{{ product.name }}
</v-card-title>
<v-card-text>
${{ product.price }}
<v-btn small class="ml-16 primary" @click="addToCart(product.id)">Add to <v-icon>mdi-cart</v-icon></v-btn>
</v-card-text>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
name: 'Home',
components: {
},
computed: {
products(){
return this.$store.getters.products
},
cart(){
return this.$store.getters.cart
}
},
methods: {
addToCart(id){
this.$store.dispatch('addToCart', id)
}
}
}
</script>
【问题讨论】:
-
在localStore中改变一个item不会触发vue的改变,所以计算出来的属性不会重新计算。
-
在计算属性中我从商店调用getter,那不应该返回最新值吗?为什么导航到其他页面并导航回主页后值会正确反映?
-
它应该而且确实如此。但是由于您只使用 localStorage 来获取一个值(它不是响应式的),getter 的值永远不会改变,因此不会重新计算计算值。
标签: javascript vue.js computed-properties