javascript - 如何在 Vue js 中解析 json 以在模板中使用它
问题描述
<template>
<div class="row w-20 " >
<div class="card col-4 ">
<ul>
<li v-for="message in conversations.messages" :key="message.messages">
{{message.text}}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
props: ['conversation_index_route'],
data() {
return {
conversations: [],
url: 'http://127.0.0.1:8000/comms/conversation/',
}
},
beforeMount() {
this.$eventBus.$on('selectConversation', this.getConversations)
this.getConversations();
},
methods: {
getConversations(id) {
console.log(this.url+id);
axios.get(this.url+ id)
.then(response => {
this.conversations = response.data;
this.conversations = JSON.parse(this.conversations.message);
console.log(this.conversations);
});
}
}
}
</script>
conversation_index_route:"http://127.0.0.1:8000/comms/conversation"
conversations:Object
all_staff_attended:false
centre_id:5
children:""
classes:""
cover_image:"https://via.placeholder.com/150x150"
created_at:"2020-05-30 19:01:59"
exited_users:null
id:257
last_id:null
messages:Array[1]
0:"{"_id":1854,"text":"This is the beginning of this conversation","createdAt":"2020-05-30 19:01:59","system":true}"
parent_users:"3016"
parents:Array[1]
staff_users:"180,181"
staffs:Array[2]
status_id:1
title:"Test"
updated_at:"2020-05-30 19:01:59"
url:"http://127.0.0.1:8000/comms/conversation/"
那么我应该编写什么代码来使用模板中的消息文本来显示文本消息?
解决方案
你必须这样做JSON.parse(conversations.messages[0]).text
。这样您就可以解析内部的对象messages
并访问其属性。
推荐阅读
- java - JUnit 不运行
- r - 如何在可变大小的 3 维数组上加快 R 循环操作?
- algorithm - 算法和确定 theta(b)
- python - 如何获得所需的尺寸作为 Tensorflow(Keras)输出?
- javascript - HTML 输入日期:不允许用户使用键盘输入未来日期
- node.js - 拒绝(TypeError):无法读取未定义的属性“setState”,未捕获(在承诺中)类型错误:无法读取未定义的属性“setState”
- c# - c#控制台应用程序按空格键而不在屏幕上显示
- ms-word - Word 加载项 (office-js) - createDocument 功能在 Word 在线中无法按预期工作
- c++ - 构造函数中需要什么,setter 函数中需要什么?
- javascript - 鼠标 - 平面上的 x 和 y 但为什么呢?