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

前端 未结 3 696
时光说笑
时光说笑 2021-01-24 03:54

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

Template:

Order\'s customer name: {{ order.customer.name }}<

相关标签:
3条回答
  • 2021-01-24 04:23

    You can use ternary operator to check

    <p>Order's customer name: {{ order.customer?order.customer.name:'' }}</p>
    
    0 讨论(0)
  • 2021-01-24 04:35

    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>
    
    0 讨论(0)
  • 2021-01-24 04:39

    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.

    0 讨论(0)
提交回复
热议问题