在几个路由器视图之间更改数据

时间:2019-02-25 14:42:15

标签: vue.js

我有两个组件,无法将数据从一个组件传递到另一组件

在第一台路由器视图中有


            data() {
            return {
                mode: true,
            }
        },
<input type="checkbox" class="switch-mode" v-model="mode" @change="$root.$emit('switch-mode', mode)">

其他是

            data() {
        return {
            filter: {
                mode: false,
                order: 'DESC'
            },
        }
    },
    mounted() {
    this.$root.$on('switch-mode', function (EventGrid) {
    console.log('Grid mode is '+EventGrid); //this works it return true,false
    this.filter.mode = EventGrid; // not working this.filter is undefined"
        })
    },

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为您的函数不知道this是什么,您应该明确地告诉它使用组件:

mounted() {
  this.$root.$on(
    'switch-mode', 
    (function (EventGrid) { ... }).bind(this)
  )
}

或者,更有效,更现代地使用箭头功能:

mounted() {
  this.$root.$on('switch-mode', (EventGrid) => { ... })
}