How to suppress “Undefined” errors before fetching data in Vue

僤鯓⒐⒋嵵緔 提交于 2019-12-02 10:14:50

问题


I have a simple page where I display some data that are fetched from the server.

Template:

<p>Order's customer name: {{ order.customer.name }}</p>

Javascript:

export default {
    data () { return { order: {} } },
    mounted () { this.fetchOrder() },
    methods: {
        fetchOrder () {
            /* get the order data asynchronously from the server */
            .success(function () { this.order = data_from_server })
        }
    }
}

Everything works just fine but in browser's console there is an error: "Cannot read property 'name' of undefined". Apparently the problem is that it takes some time to fetch the order data from the server and meanwhile it tries to access order.customer.name, which results in error, because order.customer is undefined.

How can I suppress this error? What's the best solution to this?

Of course, I can explicitly define the order structure (eg. order: { customer: {} }), but that doesn't seem nice to me, especially when the data structure grows to several-level-nested objects.


回答1:


new Vue({
  el: '#app',
  data: {
    data: {name: 'daniel'},
    data2: {}
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p v-if="data" v-text="data.name"></p>
  <p v-if="data2" v-text="data2.name"></p>
</div>

You need to render it conditionally. Since data from the backend is not accessible from the very beginning, you should add a condition to display element only when the data is ready. See example.

<p>Order's customer name: <span v-if="order" v-text="order.customer.name"></span></p>



回答2:


I think you can test for order.customer :

{{ order.customer && order.customer.name }}

if order.customer is not defined, the expression evaluation will simply stop at the first term without throwing an error.



来源:https://stackoverflow.com/questions/47033678/how-to-suppress-undefined-errors-before-fetching-data-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!