【发布时间】: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"