[Vuejs]-How to avoid accessing vue instance in multiple JavaScript files?

0👍

It depends on how complexTask changes messages.

If it replaces messages -> just return new messages and update Vue component data:

    buttonClicked: function() {
        this.complexTaskInProgress = true 
        //A method imported from another file 
        this.messages = await complexTask()
        complexTaskInProgress = false 
    }

If it modifies messages (adds, updates, removes objects), just current messages inside the function and return new array of updated messages:

    buttonClicked: function() {
        this.complexTaskInProgress = true 
        // `complexTask` copies original array of messages and return it with all require modifications
        this.messages = await complexTask(this.messages);
        complexTaskInProgress = false 
    }

Btw, this can be solved by custom Vuex plugin


Using state manager (Vuex/Redux/etc). In this case you will have one single state tree for whole application (single source of truth). For example, you can write custom Vuex plugin to fix this issue. It has access to current state and can run mutations/actions when needed. Read more about this here


Using shared state. In this case you will pass around only shared state instead of whole component instance so overhead if much lower. Also it’s simplier you implement than using state manager. Read more about this here

Leave a comment