[Vuejs]-How to update a child component when data array inserting new elements?

0👍

you should do this:

<template>
    <q-item v-for="(msg, i) in messages" :key="i" >
    <!-- q-item is a custom component of quasar framework -->
    <!-- some code here related to msg -->
    </q-item>
<template/>

<script>
export default {
    data () {
        return {
            messages: []
        }
    },
    methods: {
        submitMessage () {
        // submit the formData
        this.submitFormData({url: '/messages/new', formData})
            .then((message) => {
            this.messages.push(message)
            })
        }
    }
</script>

One of the best part of the vue is, that it dynamically update the gui elements (components), your mistake was that methods: {} was inside data() {}.

I hope it helps.

0👍

I can’t see any issues with the code, this may be related to another part of the application.

I’ve tried adding the code as is, with the exception of having this within the return of a promise, and it seems to work ok.

https://jsfiddle.net/nyaao6ec/

Vue.component('test', {
  template: `<div>
  <button @click="submitMessage('hi')">MESSAGE</button>
  <p v-for="(msg, i) in messages" :key="i" >{{msg}}
  </p>
</div>`
	,data () {
    return {
      messages: []
    }
  },
  methods: {
    submitMessage (message) {
      this.messages.push(message)
    }
  }
});

var vm = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app"><test></test></div>

can you try moving this.messages.push(message) out of the promise (and adding
a some pre-defined string)?

👤Daniel

Leave a comment