我是 vue 的新手,我正在尝试将我的 laravel 项目的前端迁移到 vue,但我遇到了一个问题,我正在尝试遍历一组名为 rooms 的提供对象并创建 div对于我的组件中的每个,并将默认 room_id 设置为房间的第一个 id。问题是什么时候在 dom (html) 中访问提供的名为“room”的 prop 数组,它可以完美地工作,但在我的组件文件的 vue 代码中,它似乎总是未定义或为空 这是我的组件 vue 代码:
export default {
created() {
//this.loadMessages(this.room_id)
console.log(this.first_room) //undefined;
console.log(this.rooms) //empty array;
},
props: ['rooms','first_room'],
computes:{
myrooms: function(){
return this.first_room;
}
},
data()
{
return{
messages: [],
newMessage: '',
room_id: 1 //for test purposes, this works,
}
},
methods: {
loadMessages(id)
{
axios.get('/messages/'+id).then(response => {
this.messages = response.data;
console.log(response.data);
});
}
}
}
组件html的重要部分
<div v-for="room in rooms">
<div class="chat-user room">
<div v-for="other in room.others">
<img class="chat-avatar img-circle" :src="other.image" alt="image" >
<div class="chat-user-name">
<a :href="'/user/' + other.id">{{ other.name}}</a>
</div>
</div>
</div>
</div>
//this all works, just for reference
我在主 vue 实例中设置传递给 prop 的值的方法
编辑:父实例代码 哦,我似乎无法访问正在传递的房间数组,因为它在代码中始终为空,但它在 html 中循环
window.App.app= new Vue({
el: '#wrapper',
data: {
messages: [],
rooms: [],
test: 'yes',
first: ''
},
created() {
this.fetchRooms();
this.first = 1;
},
methods: {
fetchMessages(id) {
console.log(id);
},
fetchRooms()
{
axios.get('/rooms').then(response => {
this.rooms = response.data;
});
}
}
});
最后我在哪里调用我的组件
<chat-messages :rooms="rooms" :first_room="1"></chat-messages>
//variables referenced from main vue instance
我真的为此扯掉了大部分头发,请提供任何帮助
最佳答案
在传递 Prop 的子组件中。
export default {
created() {
console.log(this.first_room) //undefined;
},
props: ['rooms','first_room'],
computed :{
myrooms: function(){
return this.first_room;
}
},
data () {
return {
messages: [],
newMessage: '',
room_id: 1 //for test purposes, this works,
}
},
watch: {
rooms (n, o) {
console.log(n, o) // n is the new value, o is the old value.
}
},
methods: {
loadMessages (id) {
axios.get('/messages/'+id).then(response => {
this.messages = response.data;
console.log(response.data);
});
}
}
}
您可以添加对数据属性或计算的监视以查看其值的变化。
在问题中,(看起来是这样),您在 created
生命周期中console
d 了 Prop 的值(value), Prop 的值(value)在创建子组件后,通过父组件中的 API 调用进行更改。这解释了为什么您的模板显示数据但不显示在创建的生命周期 Hook 中的 console
中。
关于javascript - 在 vue.js 组件中操作 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42946783/