开发者问题收集

Vue.js-如何将 prop 作为 json 数组传递并在子组件中正确使用它?

2020-04-27
4010

正在使用 Laravel 和 Vue。数据从 Laravel 返回到 Vue。发送给 Vue 子组件的 Vue prop 是一个 json 对象数组,但是,子组件在读取它时出错。控制台中的错误是:

"TypeError: Cannot read property 'id' of undefined". Any help would be greatly appreciated.

这是从 Laravel 返回的原始数据:

{"channels":[{"id":4,"name":"AI","created_at":"2020-04-27T15:18:01.000000Z","updated_at":"2020-04-27T15:18:01.000000Z"},{"id":2,"name":"Android Development","created_at":"2020-04-27T15:18:01.000000Z","updated_at":"2020-04-27T15:18:01.000000Z"},{"id":3,"name":"iOS Development","created_at":"2020-04-27T15:18:01.000000Z","updated_at":"2020-04-27T15:18:01.000000Z"},{"id":1,"name":"Web Development","created_at":"2020-04-27T15:18:01.000000Z","updated_at":"2020-04-27T15:18:01.000000Z"}]}

作为 Vue prop 传递给子组件的数据:

<template>
  <div id="component">
     <router-link :to="{ name: 'home' }">Home</router-link>
            <router-view></router-view>
      <br>
            <vue-chat :channels="channels"></vue-chat>
    </div>
</template>

<script>

export default {


data() {
            return {
            channels: [],
            }   
    },

methods: {

      fetchChannels() {

      let endpoint = `/channels`;

        axios.get(endpoint).then(resp => {
                    this.channels = resp.data.channels;          
                });
        },

      },

      created() {
      this.fetchChannels();
      }

}

</script>

尝试访问 Vue prop 时出错的子组件:

<template>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
            <!--    <div class="card-header">Chat</div> -->

                <div class="card-body">

                     <div class="container">

                    </div>   

                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {

    props: ['channels'],

    data() {
            return {
            activeChannel: this.channels[0].id,

        }   
    },

}
</script>

<style scoped>
@import '/sass/app.scss';
</style>
2个回答

第一次 channels 不可用,从而引发该错误,我建议将 activeChannel 定义为计算属性,如:

export default {

    props: ['channels'],

    data() {
            return {


        }   
    },
  computed:{
    activeChannel(){
     return this.channels[0]? this.channels[0].id:null,
   }

}

Boussadjra Brahim
2020-04-27

您是否使用 Chrome 上的 Vue Devtools 检查了数据 channels
您可以尝试更改以下行。

this.channels = resp.data.channels;this.channels = JSON.parse(resp.data.channels);

Sevan
2020-04-27