Facing the issue of not being able to overwrite the default initialized data (variable) in VUE.JS 2 when using the

Situation

I created a generic modal component that uses a global bus (empty VUE instance) to communicate with the modal component from any other component that utilizes it.

Problem

In the Mounted() or Created() hook for the Modal.VUE component, I am attempting to overwrite the default initialized value in order to determine which content should be displayed in the modal.

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

The above code correctly logs the actionName, indicating that the bus functionality is working as intended.

However, when setting the variable like this:

this.modalComponent == actionName

And using it like this:

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

The modalComponent value always remains empty as initialized.

Script Code:

<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
        })
    }
}

What could be the issue here? Is it related to how I'm initializing the component, the mounted() or created() hook, or the way I'm setting the new value?

UPDATE: When I console.log(this): https://i.sstatic.net/jMKxE.png

Answer №1

Your this is not the Vue instance and you should use the equality operator instead of the assignment operator. Give this a try:

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

or

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

or

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

Refer to How to access the correct this inside a callback?

Answer №2

Okay, I've come up with a more effective solution for managing this issue by utilizing state.

Original page (Implementation) :

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

Original page (Vue code to display modal component) :

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

Store.JS code :

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"

Modal component (changing content based on original page context)

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

<script>
    import { mapGetters } from "vuex"

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

This approach eliminates the need for creating a new VUE instance (bus), and resolves any issues related to using emit and on (including the initial click not functioning properly).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to modify the maximum size limit for a POST request package?

I am encountering an issue while attempting to send an array of bytes using a POST request. In my server-side implementation, I am utilizing Node.js and Express.js. Unfortunately, I am receiving error code 413 or the page becomes unresponsive ('Payloa ...

Triggering AWS Lambda functions with SQS

Utilizing AWS and SES for sending emails and SMS through a Lambda function using NodeJs. I need to make more than 1k or 500 REST API calls, with the average call taking 3 seconds to execute a single lambda function request. It is essential to process mul ...

Having difficulty with the javascript click() function in an html document

Thank you in advance for checking this out. In my web application, users can choose options from four separate drop-down menus. Once a selection is made, the software triggers a click() function that generates a new span element within a div: var activeF ...

What is the best way to upload this file in VueJS?

I've come across a file written in outdated syntax that I need to use in a VueJS Component. You can find the file here. For instance, consider these snippets from the file: var CCC = CCC || {}; CCC.STATIC = CCC.STATIC || {}; CCC.STATIC.TYPE = { & ...

A guide to retrieving all image URLs when a checkbox is selected using Javascript

My goal is to extract only image URLs from the concatenated values of price and picture URL. However, when I check different images using checkboxes, it always displays the URL of the first selected image. When I try to split the value, all the prices and ...

Utilizing Promise.all to update subdocuments with Mongoose

Encountered an error while checking the value in promiseArr, seeking assistance or suggestions for a better approach. Thanks! **Error** <rejected> { MongooseError: Callback must be a function, got [object Object] at new MongooseError (D:\P ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...

When executing the jest test with vuex-oidc, the error message "`$store` is not defined" is encountered

While testing a component that checks an OpenID response, I encountered the following error: TypeError: Cannot read property '$store' of undefined at mappedAction (node_modules/vuex/dist/vuex.cjs.js:1273:27) at src/views/OidcCallback.vue:599 ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

Using jQuery for dynamic string interpolation in input selection

Currently, I am attempting to choose an input within my dom and I am aware that it can be accomplished as follows: $("input[value='foo']") ...but, what if we were to use a variable instead? For example, if we have a variable x = 'foo' ...

What are the steps to install node.js on hosting servers like Hostinger, JustHost, and others?

Recently, I've been diving into the world of Node.js. While I have some experience with PHP, I've found that most hosting services already have a PHP interpreter installed, making it easy to work with. However, I'm now trying to figure out i ...

vue utilizeRoute method

Within my Vue.js application, I am encountering an issue with the useRoute() function. When I call this function inside a class, it returns an object successfully. However, when I place it within the @click event handler, it does not return anything. Belo ...

Are queued events in React discarded upon a state change?

As I develop a React form component with simple validation, I encounter an issue where the onBlur event of a field and the onSubmit function of the form are triggered simultaneously. If there is a change in the state during onBlur, the onSubmit function do ...

Emphasizing all words within a given set of characters

I am interested in modifying a string by making all the words enclosed in brackets bold using JSX. I have a working solution, but I am curious if there is a more efficient way to achieve this. const jsxArray = []; let unformattedString = "[name] Hi th ...

Changing Axios requests to send data as a JSON objectDo you need to know how

Looking at the title, there is a scenario where you execute a axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (erro ...

Find the current location of the scroll bar on the view port

Currently, I am utilizing the Addazle React grid for my project. However, I need to incorporate endless scrolling functionality which is not already included in this grid system. Thus, I am tasked with devising my own solution for this issue. To successful ...

Pass data to JavaScript using Node.js Express server

I recently started learning nodejs and have encountered a challenge in sending a variable from my nodejs express server to a javascript file. The code I currently have is: res.send(String(playerLives)); The variable playerLives is an integer, and I faced ...

Creating a consistent base URL for both Vue and Apache reverse proxy configurations

Currently, I am experimenting with a Vue app and testing it using pm2 in conjunction with Apache. After starting the app with pm2 and running it on port 3000, I then utilize an Apache reverse proxy to access the app through a domain and HTTPS. However, I e ...

Utilizing dynamic data in Vue-chartjs through Pinia stores

I am currently exploring how to integrate a Pinia store data with vue-chartjs in order to create dynamic charts. While referencing this example for guidance, I am facing challenges in making the chart react to changes within the store. Although I can obse ...

PHP is unable to show items containing special characters such as double quotes and apostrophes

I am facing an issue with ordering food items. Names that do not contain apostrophes work fine, but those like Pasqua Nero D'Avola Sicilia are causing problems. I have tried replacing ' with \', but the issue persists. Here is the relev ...