Far*_*nii 1 javascript vue.js vue-component vuex vuejs2
目前我正在制作一个电子商务网站。我想将用户的订单数据存储在本地存储上。这是我的代码:
详情.vue
import DataService from '../web_service/services'
export default {
name: 'details',
props: ['userId'],
data () {
return {
datas: null,
url: '/' + this.userId,
value: 1
}
},
created () {
DataService.getFindById(this.url)
.then((res) => {
this.datas = res.data.data
})
.catch((err) => {
alert('error when fetching API' + err)
})
},
methods: {
buyNow () {
let order = {
product: this.datas.name,
price: this.datas.price,
quantity: this.value
}
this.$store.commit('addOrder', order)
this.$router.push('/cart')
}
}
}
Run Code Online (Sandbox Code Playgroud)
商店.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
order: JSON.parse(localStorage.getItem("order")),
},
mutations: {
addOrder: (state, product) => {
const arrProduct = []
const parse = JSON.stringify(product)
state.order = parse
localStorage.setItem('order', parse)
}
}
})
Run Code Online (Sandbox Code Playgroud)
购物车.vue
<template>
<div class="shopCart>
<b-card-body>
<b-card-text>
<div v-if="orders" class="float-left">
<h5>{{orders.product}}</h5>
<h5>{{orders.price}}</h5>
</div>
</b-card-text>
</b-card-body>
</div>
</template>
<script>
export default {
name: 'shopCart',
data () {
return {
orders: null
}
},
created () {
this.orders = this.$store.state.order
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
当我尝试接受订单场景时,它会直接转到/cart
路线然后显示我的物品。但是,我的订单数据没有呈现。当我刷新页面时,它会显示我的订单数据。有谁知道解决方案?提前致谢 !
一切正常,除了您已将 设置order
为用于localStorage
. 因此,当您查看购物车页面时,orders.product
并且orders.price
是未定义的,即使v-if
是true
.
改变你的突变:
addOrder: (state, product) => {
const arrProduct = []
const parse = JSON.stringify(product)
state.order = product; // ? Set this to the product, not a string
localStorage.setItem('order', parse)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
50 次 |
最近记录: |