【发布时间】:2017-04-18 11:21:50
【问题描述】:
我有一个订单列表,其中每个都可以单击以查看订单详细信息。
我已经花费了数小时的调试时间来尝试理解为什么 id 属性在登录页面上为空,但通过商店和 api 调用函数看起来很好。
描述这一点的最佳方式是通过代码,因此请看一下(查看 ID 仍然具有有效值的 cmets)。
->工作路线
{ path: '/vieworder/:id', component: ViewOrder, props: true },
-> 路线推送到详细信息页面:
methods: {
...mapActions(['getOrders']),
init() {
this.getOrders()
},
viewOrder: function(order){
this.$router.push('/vieworder/' + order.id)
}
},
-> VIEWORDER.VUE(ID 在模板中为 NULL..)
import * as types from '../store/mutationtypes'
import { mapGetters, mapActions } from 'vuex'
export default {
name: 'ViewOrder',
props: {
id: {
type: String,
required: true
}
},
created() {
this.$store.dispatch('getOrderById', {
id: this.id
})
console.log('The id is now : ' + this.id)
},
computed: {
...mapGetters(["order"])
}
}
<template>
<div class="col-sm-10 col-sm-offset-1">
<h4>{{ order.id }}</h4>
</div>
</template>
--> STORE AND GETORDERBYID(此处的 ID 值正确...)
export default new Vuex.Store({
state: {
orders: [],
order: null
},
getters: {
orders: state => state.orders,
order: state => state.order
},
actions: {
getOrders({ commit }) {
api.getOrders().then(orders => commit(types.UPDATE_ORDERS, orders))
},
getOrderById({ commit }, { id }){
console.log("In Store now - Do we have an id ? : " + id)
api.getOrderById(id).then(order => commit(types.UPDATE_ORDER, order))
},
etc.etc.etc...
--> API 调用返回数据
getOrderById(orderId){
return axios.get('http://localhost:3000/Orders/' + orderId)
.then(response => response.data)
},
--> API 调用返回的示例数据
"Orders": [
{
"id": 123456,
"PaidDate": "2017-01-12",
"AppId": "KLM-UXI-NIX-FIX",
"TicketType": "Barn - Enkeltbillett",
"TicketCount": 1,
"OrderSum": "17",
"MediaChannel": "Android",
"StatusCode": "08-12-34-56-78",
"PaymentOption": "VISA"
},
【问题讨论】:
-
不要使用
getOrderById({ commit }, { id }),因为你已经在使用来自对象的id,getOrderById({ commit }, id) -
哇!.. 这是一个快速的赞扬@AmreshVenugopal :) 所以这可能是我编程头痛的原因吗?我现在马上试试。我会尽快回复你...
-
在 VIEWORDER.VUE 中你应该使用
mounted()而不是created()。如果不能解决问题,请在mounted()hook:this.id = this.$route.params.id -
如果订单为空,可以尝试在 vuex 中将
getOrderById({ commit }, { id })更改为getOrderById({ commit }, id)并在mounted() 挂钩中将其称为this.$store.dispatch('getOrderById', id)。您也可以像<div class="col-sm-10 col-sm-offset-1" v-if="order.id">这样检查订单是否存在,以避免在获取数据之前出错。 -
@TerjeNygård 您收到错误的原因是因为
order是异步填充到存储中的。意思是,当组件被挂载时,order是null。您的模板使用order.id,当它首次呈现时,基本上是null.id,这是无效的。稍后,当您的getOrderByIdajax 调用完成时,订单 具有 一个值。 Wostex 建议使用v-if会阻止组件尝试访问order.id,直到order实际具有值。
标签: vue.js vuejs2 vue-router vuex