首页 > 解决方案 > 渲染后Vue将更新的道具发送给孩子

问题描述

VUE渲染后如何更新PROPS?

家长

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

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

孩子

<template>...</template>

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

由于窗口消息在 myComponent 渲染后稍后出现..在这种情况下没有任何更新,只是得到空数组..在这种情况下收听更新道具的最佳方法是什么?

标签: vue.jsvue-component

解决方案


myProps在 vue 实例中定义为 data 属性,然后window.onmessage在挂载的钩子中运行:

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}}}),
});

推荐阅读