2017-07-27 88 views
-1

令人困惑的标题,我不知道如何写它。 所以我有一个组件,它接受一个数组的道具。 我想要做的是在array.push()我想要一个函数来触发该数组元素。vuejs组件阵列推送观察者

所以这是一个警告敬酒信息,我希望它保持3秒钟。所以我正在考虑像

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

但我想我可能会错过这里的东西。我如何获得最新的推送对象的参考,所以我确保dismiss方法调用正确的警报?观看甚至是正确的方式去做这件事?

+1

'变种最后=此[this.length-1]'? – lloyd

+0

但是当dismiss()被调用时,这会让我超出界限的异常,因为数组对象不存在,它仍然是被调用的 – 173901

+0

是否有其他数组操作可行?片?流行? –

回答

0

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

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

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>