VUE.JS 2 : 无法覆盖挂载钩子上的默认初始化数据(变量)

VUE.JS 2 : Unable to overwrite default initialized data (variable) on mounted hook

场景

我有一个通用模态组件,我在其中使用全局总线(空 VUE 实例)与正在使用它的任何其他组件的模态组件通信。

问题

在 Modal.VUE 组件的 Mounted() 或 Created() 挂钩中,我试图覆盖默认的初始化值,我需要弄清楚哪些内容将显示在模态中。

console.log("Selected action is : " + actionName)

... 提示正确的 actionName,所以总线功能就在那里..

但是当这样设置变量时:

this.modalComponent == actionName

.. 并像这样使用它:

<h2 v-if="modalComponent == 'refund'">Refundér</h2>
<h2 v-if="modalComponent == 'empty'">Not defined</h2>

.. modalComponent 值始终为空(初始化时)

脚本代码:

<script>

import bus from '../global/bus.js'

export default {
    name: "modal",
    data(){
        return {
            modalComponent: "empty"
        }
    },
    mounted() {
        bus.$on('on-action', function (actionName) {
            console.log("Selected action is : " + actionName)
            this.modalComponent == actionName
        })
    }
}

那我做错了什么?这是我初始化的方式吗? mounted() 或 created() 钩子有问题吗?或者..我设置新值的方式?

更新: 当 console.log(this) 时:

你的this不是Vue除了用相等运算符代替赋值运算符。尝试

const self = this
bus.$on('on-action', function (actionName) {
    console.log("Selected action is : " + actionName)
    self.modalComponent = actionName
})

bus.$on('on-action', function (actionName) {
    console.log("Selected action is : " + actionName)
    this.modalComponent = actionName
}.bind(this))

bus.$on('on-action', actionName => this.modalComponent = actionName)

How to access the correct this inside a callback?

好吧...我想出了一个更好的方法来使用状态来处理这个问题..

源页面(用法):

<a @click="toggleModal('refund')" class="btn btn-success btn-fixed-
  width">Refundér</a>
<a @click="toggleModal('move')" class="btn btn-success btn-fixed-
  width">Flytt</a>

源页面(显示模态组件的Vue代码):

toggleModal: function(actionName){
            this.$store.dispatch('switchModalComponent', {
                modalComponent: actionName
            })
            this.showModal = true;
        }

Store.JS代码:

export default new Vuex.Store({ 
    state: {
        visibleModalComponent: "empty"
    },
    getters: {
        visibleModalComponent: state => state.visibleModalComponent
    },
    actions: {
      switchModalComponent({ commit }, modalComponent){
        commit(types.VISIBLE_MODAL_COMPONENT, modalComponent)
    },
     mutations: {
         [types.VISIBLE_MODAL_COMPONENT] (state, modalComponent) {state.visibleModalComponent = modalComponent}
    }

Mutationtypes.JS

export const VISIBLE_MODAL_COMPONENT = "VISIBLE_MODAL_COMPONENT"

模态组件(根据源页面上下文切换内容)

<h1>{{ visibleModalComponent.modalComponent }}</h1>

<script>
    import { mapGetters } from "vuex"

    export default {
        name: "modal",
        computed: {
            ...mapGetters(["visibleModalComponent"])
        }
    }
</script>

这样...您不需要为新的 VUE 实例(总线)和使用 emit 和 on 的问题而烦恼(由于第一次点击不是 -工作问题)。