简体   繁体   中英

Display Axios response data in Vue.JS

I wrote this Vue.JS code to display JSON response received from PHP file in a conversation format. My current code looks like this:

    const app = new Vue({
    el: "#chatview",
    data: {
            messages:[],
            txtInput: '',
            mid:0
        },
    methods:{

    GetBubbleType: function (name){     
                    if(name === "AI")
                     return "yours messages";
                    else
                     return "mine messages";
                },
   },   
   mounted(){
        axios.post('./ConversationGetter.php',{
            function2call: 'getRecord',
            id: 1,
        }).then( response =>  {console.log(response.data);
         this.data=response.data;
        }).catch(error => {});

        },      
  template: `
  <div style ="font-family:Open Sans;font-size:16px">
  <div v-for="message in messages">
    <div class="fade-in">
      <div v-bind:class="GetBubbleType(message.name)">
        <div class="message last">
          <p>{{message.message}}</p>
        </div>
      </div>
    </div>
  </div>
  <form @submit.prevent="sendMessage('out')"  id="person-form">
    <p>
      <input type="text" placeholder="Enter Your Query Here"style=" border-radius=25px" v-model="txtInput">
      </input>
      <input type="submit" placeholder="Send"style=" border-radius=25px">
      </input>
    </p>
  </form>
</div>

  `
})

The response recieved from PHP is (written on console):

{
  "data": [
    {
      "Modified_Time": "2019-12-13T16:08:36+05:30",
      "$currency_symbol": "$",
      "Message": "Hey!",
      "Created_Time": "2019-12-13T16:08:36+05:30",
      "Name": "AI",
    },
    {

      "Modified_Time": "2019-12-13T16:08:27+05:30",
      "$currency_symbol": "$",
      "Message": "Yo!",
      "Created_Time": "2019-12-13T16:08:27+05:30",
      "Name": "Me",
    },

  ],
}

The return line of PHP is: echo $result; return $result; echo $result; return $result;

For some reason, it does not show the messages in the chat view.. Where am I going wrong?

Your template is doing a v-for on the messages object from the component's data . However, you're assigning this.data=response.data . That's creating a property data on the component instance, not assigning the messages value.

Instead, just change this.data=response.data to this.messages=response.data.data .

As noted in the comments, your response body contains a data array at the root, and Axios returns the response body in response.data , hence response.data.data is what should be assigned to this.messages .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM