【问题标题】:vuejs component array push watchervuejs 组件数组推送观察者
【发布时间】:2018-01-03 21:04:14
【问题描述】:

标题混乱,不知道怎么写。 所以我有一个组件,它接受一个数组的道具。 我想做的是在 array.push() 上,我想要一个函数来触发该数组元素。

所以这是一条警报消息,我希望它保持 3 秒。所以我在想类似的东西

watch: {
    arrayObj: function () {
        let self = this
        setTimeout(function() {
            self.dismiss(this.id)
        }, 3000)
    }
}

但我想我可能在这里遗漏了一些东西。如何获取最新推送对象的引用,以确保解除方法调用正确的警报?观看甚至是解决此问题的正确方法吗?

【问题讨论】:

  • var last = this[ this.length-1 ] ?
  • 但是当调用dismiss()时这会让我越界异常,因为数组对象不存在并且它仍然是被监视的对象
  • 是否可以进行其他数组操作?片?流行音乐?
  • 你到底为什么要这样做呢?这似乎更像是代码异味,而不是 javascript 或 vue 的实际问题。

标签: javascript arrays vue.js


【解决方案1】:

我并不完全清楚您想要获得什么行为,但在我看来,您需要跟踪最新推送的项目并将其传递给您的组件。该组件将监视latestPushed 并采取相应措施。

如果可以重复最新推送的项目,则推送重复值时您不会看到更改。在这种情况下,将事件总线 prop 传递给组件并在父级推送时发送和事件是有意义的。

new Vue({
  el: '#app',
  data: {
    bus: new Vue(),
    theArray: [1]
  },
  methods: {
    push() {
      const value = Math.floor(Math.random() * 10);
      this.theArray.push(value);
      this.bus.$emit('push', value);
    }
  },
  components: {
    toasterNote: {
      props: ['bus'],
      data() {
        return {
          active: false,
          latestPush: null,
          timer: null
        };
      },
      created() {
        this.bus.$on('push', (newValue) => {
          this.latestPush = newValue;
          this.active = true;
          clearTimeout(this.timer);
          this.timer = setTimeout(() => this.active = false, 3000);
        });
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <div>{{theArray}}</div>
  <button @click="push">Push</button>
  <toaster-note inline-template :bus="bus">
    <div v-if="active">
      You pushed {{latestPush}}
    </div>
  </toaster-note>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多