代码之家  ›  专栏  ›  技术社区  ›  Euklides

如何从外部更新Vue组件道具对象?

  •  0
  • Euklides  · 技术社区  · 6 年前

    我需要更新 props 来自Vue外部的Vue组件的对象。我有一个可行的解决方案,但我得到一个警告,我想摆脱。

    我创建了一个这样的vue组件:

        this.vm = return new Vue({
          render: h => h(component, {
            props: propsData,
          })
        }).$mount(el);
    

    然后在一个函数中,我从vue外部更新道具,如下所示

        this.updateProps = function (props) {
           const children = this.vm.$children;
           const firstChild = children && children[0];
           if (!firstChild) {
             return;
           }
           _.each(_.keys(firstChild.$props || {}), (key, i) => {
             firstChild.$props[key] = props[key];
           });
        }
    

    这是有效的,但我得到这个警告信息:

    [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "xxxx"

    在没有得到警告的情况下,应该如何正确地完成这项工作?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Vladislav Ladicky    6 年前

    不能。如警告所示,请在组件中创建自己的数据并使用道具作为初始值,或使用计算属性。例如:

    props: ['initialCounter'],
    
    data: () => ({
      counter: this.initialCounter
    })
    

    或:

    props: ['size'],
    
    computed: {
      normalizedSize () {
        return this.size.trim().toLowerCase()
      }
    }