Reputation: 27
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
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
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
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