困扰了我很久的问题,实在没有办法,只能仰仗大神了。
我的想法是:通过 watch
监控 snacks
数组是否发生变化,一旦发生变化,就触发匿名函数,通过 this.$refs.snackbar.open()
將提示框打開,但是就出現錯誤了?
vue.esm.js?65d7:479 [Vue warn]: Error in callback for watcher "snacks": "TypeError: this.$refs.snackbar.open is not a function"
<template>
<div id="app">
<router-view></router-view>
<div class="snackbar-list" v-for="snack in snacks">
<md-snackbar :md-position="vertical + ' ' + horizontal" ref="snackbar" :md-duration="duration">
<span>{{ snack.message }}</span>
<md-button class="md-accent" @click="$refs.snackbar.close()">確定</md-button>
</md-snackbar>
</div>
</div>
</template>
<script>
export default {
name: 'grouper',
data () {
return {
vertical : 'top',
horizontal : 'center',
duration : 4000,
snacks : this.$store.state.snacks
}
},
mounted : function(){
this.$store.state.snacks.push({ message : 'OK' });
this.$store.commit('popupSnack',{ message : 'NO' });
},
watch : {
snacks : function(val, oldVal){
this.$refs.snackbar.open()
}
}
}
</script>
我也知道這個 this
不是指向 vue 实例,但也不知道怎么解决,才能够用的到 $refs
this 应该是指向实例的,你这个 ms-snackbar 是 Vue 组件吗,是的话应该通过 props 来控制。