2

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?

3 Answers 3

3

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}}}),
});
Sign up to request clarification or add additional context in comments.

3 Comments

got Error : [Vue warn]: Error in render: "TypeError: Cannot read property 'updatedPopup' of undefined" that means { props: { myProps: this.myProps } where looks like { props: { myProps: underfined.myProps } in console
Try it out without this
has to be changed ES6 render: h => h(..). to function render: function(h) {h(...)} for this to be worked
1

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.

1 Comment

for simple cases he could use observable api
0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.