Vue计算未定义

时间:2019-10-15 14:02:45

标签: vue.js

在我的组件中,我有:

    mounted () {
        this.$store.dispatch('loadTickets')
    },
    computed: {
            ticketLast() {
            return this.$store.state.tickets.slice(-1)[0];
            },
             ...mapState([
            'tickets'
            ]),
    }

商店:

 state: {
      tickets: []
    }
    actions: {
      loadTickets ({ commit }) {
        axios
        .get('/tickets.json')
        .then(r => r.data)
        .then(tickets => {
         commit('SET_TICKETS', tickets);
         })
       },
    },
    mutations: {
      SET_TICKETS (state, tickets) {
      state.tickets = tickets
      },
    }

在模板中

<div class="form-info-grid">
   <div class="form-info">
     {{ ticketLast.number }}
    </div>
    <div class="form-info">
      {{ ticketLast.date | formatDate }}
    </div>
  </div>

显示正确的值,但是在控制台中我得到:

  

渲染错误:“ TypeError:无法读取属性'number'   未定义”

关于为什么会这样的任何想法?

1 个答案:

答案 0 :(得分:0)

以下代码段解决了该问题-但是您是否看到所显示数据的闪烁? (有时)这是 async 函数-您没有tickets.slice(-1)[0],因为有一段时间票证数组为空-而且空数组没有最后一个元素,并且因此,此“最后一个元素”不能具有 number 属性。

(我必须编辑您的示例代码,使其与模型JSON一起使用。)

const store = new Vuex.Store({
  state: {
    tickets: []
  },
  actions: {
    loadTickets({
      commit
    }) {
      fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(tickets => {
          commit('SET_TICKETS', tickets)
        })
      /*axios
        .get('/tickets.json')
        .then(r => r.data)
        .then(tickets => {
          commit('SET_TICKETS', tickets);
        })*/
    },
  },
  mutations: {
    SET_TICKETS(state, tickets) {
      state.tickets = tickets
      console.log(state.tickets)
    },
  }
})

new Vue({
  el: "#app",
  store,
  mounted() {
    this.$store.dispatch('loadTickets')
  },
  computed: {
    ticketLast() {
      return this.$store.state.tickets.slice(-1)[0] || {
        id: '',
        title: Date.now()
      };
    },
    /*...mapState([
      'tickets'
    ]),*/
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.1/vuex.min.js"></script>

<div id="app">
  <div class="form-info-grid">
    <div class="form-info">
      {{ ticketLast.id }}
    </div>
    <div class="form-info">
      {{ ticketLast.title}}
    </div>
  </div>
</div>