【问题标题】:Vue.js components data not updating when props are updated更新道具时Vue.js组件数据不更新
【发布时间】:2018-08-16 14:46:15
【问题描述】:

我对此感到非常困惑,因为我有另一个简单的组件正在工作并且遵循与错误组件相同的样式。

我有一个组件 alertBox :

var alertBox = {
template: '\
    <transition name="fade">\
      <div class="alert" :class="[status]">\
        {{ message }}\
        <button @click="close" type="button" class="close" aria-label="Close">\
          <span aria-hidden="true">&times;</span>\
        </button>\
      </div>\
    </transition>',
    props: {
      alertMessage: {
        type: String,
        required: true
      },
      alertStatus: {
        type: String,
        required: true
      }
    },
    data: function() {
      return {
        status: this.alertStatus,
        message: this.alertMessage
      };
    },
    methods: {
      close: function() {
        console.log('ran close')
        this.$emit('close-alert');
        this.crazyTest();
      },
      crazyTest: function() {
        console.log(this.alertStatus)
        console.log(this.alertMessage)
        console.log(this._props)
        console.log(this.$props)
        console.log(this._data)
        console.log(this.message)
        console.log(this.status)
      }
    }
}

哈哈懒得去掉 crazyTest 方法!

alertBox 用于两个区域,一次在父级上,一次在父级内的组件上。

在父节点上,它具有如下数据绑定: :alert-message="alerts.createEngineerMessage" :alert-status="alerts.createEngineerStatus"

组件模板是这样的: :alertMessage="alerts.createCompanyMessage" :alertStatus="alerts.createCompanyStatus"

在另一个方法中,在用户操作之后,父级上的警报对象中的数据会在显示警报框之前更新。我的 crazyTest 方法证实了这一点,并显示道具已使用组件中的新数据进行了更新。但是数据属性消息和状态不会更新。

所有值都针对反应性进行了初始化。

【问题讨论】:

    标签: javascript vuejs2 vue-component


    【解决方案1】:

    当组件被渲染时,你的数据就设置好了。这就是为什么没有更新。

    要解决这个问题,你可以采取两种方式:

    1) 观察你的 props 的变化并更新你的数据。

    watch: {
        alertMessage: function (val) {
          this.data.message = val
        },
    }
    

    2) 直接使用您的道具,无需复制到数据。

    <transition name="fade">\
          <div class="alert" :class="[errorStatus]">\
            {{ errorMessage }}\
            <button @click="close" type="button" class="close" aria-label="Close">\
              <span aria-hidden="true">&times;</span>\
            </button>\
          </div>\
        </transition>'
    

    【讨论】:

    • 我忘了渲染!令人困惑的是我拥有的另一个组件完全相同但它工作,唯一的区别是在更新数据的操作之后我会隐藏一个表单并显示另一个包含新数据的组件。非常感谢!
    • 刚刚意识到,如果我有 v-if="booleanValue" 而不是 v-show="booleanValue" 数据会以我使用它的方式更新,对吗?
    • 没错。但我认为它会有点脏;)
    • 考虑使用 computed 属性而不是 watcher。 vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property
    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 2019-08-03
    • 2015-07-13
    • 2018-07-02
    • 2019-06-13
    • 2018-08-09
    • 2019-07-08
    • 2017-02-09
    相关资源
    最近更新 更多