Assign the "this" keyword of App.vue to the Vuex state

I have discovered a workaround for accessing vue-router and other services that only works within a Vue component. By saving the "this" of the Vue app in the state of Vuex within the created option of App.vue.

Is this a good approach or could it potentially cause problems in the future?

Instead of using:

this.$router.push('route-name')

directly from a component, I am now storing the this keyword as a key called context in the state. Then, I use context instead of this in Actions like so:

state.context.router.push('route-name')
and it works.

My question is if this is a valid solution or not.

Answer №1

In my opinion, relying on the direct usage of this is not a recommended solution. It would be better to utilize actions or getter returned values within a Vue file instead of directly using them in an action.

Allow me to provide an example along with an explanation:

Example:

Getter:

export function getRedirect(state){
 return state.routerName
}

Vue file:

<template>
Page 
<button @onClick="redirect" > Redirect </button>
</template>
<script>
import {mapGetters} from 'vuex'
export default: {
   computed:{
      ...mapGetters('VuexStoreName',['getRedirect'])
   },
   methods:{
        redirect(){
            this.$router.push(this.getRedirect)
        } 
   }
}
</script>

Instead of directly accessing the redirect within a JS file and passing it as a parameter or fetching it through the state, it's advisable to handle it appropriately within a Vue file.

The issue with assigning this in the state is that the saved instance will not update automatically when it changes, requiring manual updates everywhere. On the other hand, referencing this in a Vue file ensures its constant updation.

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

Issues with changing background colors using Jquery animate

I am attempting to create a fading background color effect when a button is clicked. Currently, I can change the background color using this code: $("#" + lblqty).css("background","#e9f1ff"); However, when I try to use the animate function as shown below ...

Is there a Google Maps feature that displays clusters in a dropdown

Currently, I am utilizing Google Maps to place pins all over the world and implementing markercluster.js to cluster those pins when they are nearby. One feature I am trying to incorporate is the ability to hover over a cluster of pins and have a dropdown d ...

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

Whenever a button is clicked in Vue.js 2, the $refs attribute is returning an empty object to me

My attempts to retrieve the value of a ref from my input in the console are proving unsuccessful as it keeps returning an empty object. I utilized the $emit function to pass the function from the child component to the parent component. When I tried cons ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors. Looking to switch components using v-if and passing different properties. Here's a small example: Currently, when switching from 'blue' to 'red ...

React Redux causing React Router to display empty pages

In my App.js, the following code is present: const Index = asyncRoute(() => import('~/pages/index')) const Register = asyncRoute(() => import('~/pages/register')) const AddDesign = asyncRoute(() => import('~/pages/add-des ...

Is it feasible to establish a direct link between an Angular.js application and Dynamodb? Are there any other solutions available to eliminate the need for a backend

Personally, I believe that removing the backend could be a successful strategy for addressing sysadmin/scale issues. Do you agree with this approach? Is there a proven method for eliminating the backend in web applications that require database access? I& ...

Using parseFloat in JavaScript for German number formatting

Currently, I am working on incorporating a Vue.js component that is inspired by the example provided in this link: https://jsfiddle.net/mani04/bgzhw68m/. This is the structure of my source code: computed: { displayValue: { get ...

A guide on launching a modal within a Vue router

Does anyone have a solution for displaying a modal window using the code this.$modal.showForm('Login)' in vue-router? It works fine when I do it in a Vue component, but I'm running into an error "Cannot read property '$modal' of un ...

Generating dynamic dropdown lists with JavaScript for variable arrays

I've been scouring the internet for quite some time now, both on this platform and through Google searches, but I can't seem to find what I'm looking for. (Apologies if I missed it and this comes across as a repetitive or annoying question.) ...

Switching images using jQuery

Issue I'm feeling overwhelmed by the abundance of JavaScript code hints and finding it difficult to determine where to begin. Any assistance would be greatly appreciated. Essentially, I have a primary full-screen background image set in the CSS on t ...

Utilizing a dynamic form action connected to an Express route

I've been grappling with creating an HTML form in my nodejs application that directs to the appropriate express route upon submission. After researching online, I stumbled upon a potential solution as outlined below: <script> $('#controlPa ...

Using the power of AJAX, retrieve data from a PHP script and showcase the response within

Within my HTML file, I have implemented a feature that allows users to input a value. To validate this input, I created a PHP script that checks if the entered value exists in the database. The script returns the following JSON response: {"active":true} ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

Dealing with AJAX error in pure JavaScript

I have been attempting to address AJAX errors using the code below, but unfortunately, it does not seem to be effective. function ajaxPost(url, data, success, error) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

In jQuery, there seems to be an issue where the click event is not functioning properly on an element that has been

I am using jQuery to append items, but I am having trouble binding events to the appended items. My appending code looks like this: var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px; ...