【问题标题】:Laravel Vue SPA: How can the prop which is an array retrieved by axios be passed to a child component?Laravel Vue SPA:如何将由 axios 检索到的数组 prop 传递给子组件?
【发布时间】:2020-10-31 12:20:17
【问题描述】:

Laravel Vue SPA:如何将 axios 检索到的数组 prop 传递给子组件?

json 对象在somedomain.com/channellist 正确可用。 然后由axios 检索,然后传递给子组件。

如何将其传递给子组件,以便正确呈现activeChannel

任何帮助将不胜感激。

Vue 子组件:

<template>
    <div id="app">      
             <p>{{ activeChannel }}</p>
    </div>
</template>

<script>

  export default {
 
    props: ['channels'],

    data() {
            return {
            
            activeChannel: this.channels[0].id,
           
        }   
    },
   
   methods: {
    
        
    },
    
   components: {
     
   },
    
   created() {
     
  }
}
</script>
<style>
    #app {
        margin-left: 1em;
    }

    .heading h1 {
        margin-bottom: 0;
    }
</style>

Vue父组件:

<template>
    <div id="app">      
       <vue-chat :channels="channels"></vue-chat>
       <div v-for="channel in channels" :key="channel.id">
          <label>Channel Name</label>
          <input type="text" readonly :value="channel.name">
          <br>
          <label>Channel Name</label>
          <input type="text" readonly :value="channel.created_at">
       </div>
    </div>
</template>

<script>

  export default {
 
    data() {
      return {
        
        channels: [],
        
      }
    },
   
   methods: {
    
        getChannels(){
            this.loading = true
            var url = "/channellist"
                
            axios
              .get(url)
              .then(response => (this.channels = response.data.channels))
            },     
    },
    
    watch: {

    },
    
    components: {
     
    },
    
    created() {
     
      this.getChannels()
   
     }
  }
</script>
<style>
    #app {
        margin-left: 1em;
    }

    .heading h1 {
        margin-bottom: 0;
    }
</style>

从 Laravel 返回的 json 对象 somedomain.com/channellist:

{"channels":[{"id":1,"name":"channel 1","created_at":"2020-07-10T06:03:14.000000Z","updated_at":"2020-07-10T06:03:14.000000Z"},{"id":2,"name":"channel 2","created_at":"2020-07-10T06:03:14.000000Z","updated_at":"2020-07-10T06:03:14.000000Z"},{"id":3,"name":"channel 3","created_at":"2020-07-10T06:03:14.000000Z","updated_at":"2020-07-10T06:03:14.000000Z"}]}

【问题讨论】:

  • 您粘贴的代码应该可以工作...您遇到了什么问题?
  • 在浏览器控制台出现子组件错误:[Vue warn]: Error in data(): "TypeError: this.channels[0] is undefined"

标签: arrays json vue.js axios


【解决方案1】:

问题是在请求得到解决之前。在此之前,您将传递一个空数组作为道具。所以调用channels[0].id 会导致

TypeError: this.channels[0] 未定义

错误,因为通道中没有索引 0。

一个快速修复将是

   <vue-chat v-if="channels.length && channels[0].id" 
             :channels="channels">
    </vue-chat>

更强大的解决方案是在您的子组件上创建一个 watcher,当道具可用时设置所需的值。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2018-06-20
    • 2021-11-02
    • 2018-12-03
    • 2021-01-21
    • 2019-10-07
    • 2021-11-06
    • 2018-07-09
    相关资源
    最近更新 更多