【问题标题】:Vue send updated props to child after rendering渲染后Vue将更新的道具发送给孩子
【发布时间】:2021-03-05 13:53:06
【问题描述】:

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.js vue-component


    【解决方案1】:

    myProps定义为vue实例中的数据属性,然后在挂载的钩子中运行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}}}),
    });
    

    【讨论】:

    • 得到错误:[Vue 警告]:渲染错误:“TypeError:无法读取未定义的属性 'updatedPopup'” 这意味着 { props: { myProps: this.myProps } 看起来像 { props: { myProps: underfined.myProps }在控制台中
    • 不用this试试看
    • 必须将 ES6 render: h =&gt; h(..). 更改为函数 render: function(h) {h(...)} 才能使 this 工作
    【解决方案2】:

    如果您想从 vanilla 与 Vue 应用程序交互,除了其他答案之外,请使用方法。

    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>

    【讨论】:

      【解决方案3】:

      除了 Boussadjra 的回答,我还建议使用 state library such as Vuex,它允许您跨页面共享状态。

      但对于简单的数据共享,Boussadjra 的回答也可以。

      【讨论】:

      • 对于简单的情况,他可以使用 observable api
      猜你喜欢
      • 2017-06-04
      • 2022-08-03
      • 2017-01-13
      • 2018-12-30
      • 2017-08-03
      • 1970-01-01
      • 2018-05-03
      • 2018-11-24
      • 2019-02-03
      相关资源
      最近更新 更多