如何在 Vue js 中解析 json 以在模板中使用它

Posted

技术标签:

【中文标题】如何在 Vue js 中解析 json 以在模板中使用它【英文标题】:How to parse json in Vue js to use it in template 【发布时间】:2020-10-14 05:22:15 【问题描述】:
<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/"

那么我应该编写什么代码来使用模板中的消息文本来显示文本消息?

【问题讨论】:

试试 message[0].text 。它的工作,因为文本在消息数组中。 @Archaana 【参考方案1】:

你必须做JSON.parse(conversations.messages[0]).text。这样您就可以解析 messages 中的对象并访问其属性。

【讨论】:

heyyy hiiii ,这是他要我做的事情 .. 但我能知道在哪里准确地编码这一行 .. 我被卡住了.. 很抱歉问这个 嘿,谢谢伙计,我已经知道了...我在 v-for 中的 JSON.parse(conversations.messages).text JSON.parse(sub_categories) 效果很好,谢谢

以上是关于如何在 Vue js 中解析 json 以在模板中使用它的主要内容,如果未能解决你的问题,请参考以下文章