ozzot
ozzot

Reputation: 27

Vue send updated props to child after rendering

How to update PROPS after rendering in VUE?

PARENT

const myProps = [];
window.onmessage = function(data) {
  myProps.push(data)
}

new Vue({
  el: el || '',
  render: h => h(myComponent, {props:{myProps: myProps}}),
});

CHILD

<template>...</template>

export default {
  props: ['myProps'],
  ....
}

Due to window message comes later after myComponent rendered.. in this case no any updates, just got empty Array.. What the best way to listen updates props in this case?

Upvotes: 2

Views: 235

Answers (3)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

define myProps as data property in vue instance then run window.onmessage in mounted hook :

new Vue({
  el: el || '',
  data(){
    return{
      myProps : []
   } 
 },
  mounted(){
   window.onmessage = (data)=> {
       this.myProps.push(data)
   }
 },
  render: function(h){return h(myComponent, {props:{myProps: this.myProps}}}),
});

Upvotes: 3

Pierre Said
Pierre Said

Reputation: 3820

In addition to other answer if you want to interact with a Vue app from vanilla use a method.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    counter: 0
  },
  methods: {
    inc() {
      this.counter += 1;
    }
  }
})

window.inc = () => {
  app.inc();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h3>Vue app : </h3>
  Counter : 
  {{ counter }}
</div>




<h3>Outside of vue : </h3>

<button onclick="inc()">
  Inc
</button>

Upvotes: 0

hvaughan3
hvaughan3

Reputation: 11105

In addition to Boussadjra's answer, I would also recommend using a state library such as Vuex which allows you to share state across pages.

But for a simple data share, Boussadjra's answer will work as well.

Upvotes: 1

Related Questions