Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile.

The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up, but it doesn't work in reverse (my-profile -> another profile the button disappears).

Currently, the button only shows up when I switch from a different route (e.g., from the homepage to my profile).

On my Profile.vue

<v-btn
    v-if= "isUserProfile()"
    outline
    large
    fab
    v-on="on"
    color="indigo">
<v-icon>edit</v-icon>
</v-btn>

A watcher in Profile.vue checks for changes in the URL/router parameters.

watch: {
    '$route.params.username': {
        immediate: true,
        handler (value) {
            this.username = value
            this.getId()
            this.isUserProfile()
        }
    }
},

Using the method:

isUserProfile () {
    return (this.$store.state.route.params.username === this.$store.state.user.username)
},

The button should appear every time I switch to my own profile from another one since it works in the opposite scenario. However, there seems to be a problem as demonstrated in this example gif where my profile is "123123":

https://gyazo.com/cf47036bfb60cc6490c538e50a32db81

Manually changing the parameters in the URL by switching between profiles reveals the inconsistency of the button display. It should always be visible when switching back to my profile.

Answer №1

Well, it turns out that the solution is quite straightforward and the complexities of converting it into a computed value were unnecessary, as I just verified (although many would argue that using a computed value is a better practice).

Solution: Instead of using v-if:isUserProfile, consider using v-show:isUserProfile; this way, the button will change based on what needs to be achieved.

I am now going to delve into https://v2.vuejs.org/v2/guide/conditional.html for more insights.

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

Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution. Here is my .ts file: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Feedba ...

issue with leaflet vue3 component showing incorrect marker popup when clicked

I am dynamically loading markers based on the bounding box from an API using a Pinia store. These markers are stored in the itemsList property of my map wrapper component map-view. The markers are rendered as circlemarkers inside a Vue-for loop. As I navi ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Setting custom parameters ($npm_config_) for npm scripts on Windows allows for more flexibility and customization in

I'm struggling with passing custom parameters from the command line to npm scripts in my package.json file. Despite researching on various platforms, including Stack Overflow, I haven't found a solution that works for me. Here's what I' ...

Tips for determining the size and identifier of a newly appended element in jQuery?

Struggling to create a select element with a width="347px" and id="select-box-1". I attempted to use .append("select"), but my search on .append() didn't yield the desired results. Unsuccessful Attempt: .append("< ...

Utilizing MongoDB query for geoLocation with maxDistance parameter

Customer location: customerCoordinates: [83,24] stores: { id:1, location: {coordinates:[85,44]...} maxRadiusDelivery: 2000 //meters }, { id:2, location: {coordinates:[82,34]...} maxRadiusDelivery: 100 //meters } Query: db.wh.find({ 'locati ...

Having trouble with some JS and Jquery codes not functioning properly in IE until the page is refreshed a few times. Any suggestions on how to fix this issue?

My code seems to be experiencing issues in Internet Explorer where some of the JS and jQuery codes are not functioning correctly initially, but start working after refreshing the page a few times. Any thoughts on why this could be happening? Here is the ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Modify the tooltip of the selected item in an ng-repeat loop in AngularJS

Upon clicking an element, a function is executed which, upon successful completion, should change the tooltip of that specific element. Within an ngRepeat loop, I have multiple elements displaying the same tooltip. However, I only want to update the toolt ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

What is the process of invoking a function on a specific element when it is encapsulated within an if statement in Meteor.js

Here is an example: {{#if currentUser}} <li><a class="waves-effect waves-light btn modal-trigger modal-close" href="#upload">Upload Image</a></li> {{/if}} Currently, I am implementing the following: Template.MasterLayout.onRe ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...

Understanding the extent of variables in Javascript

I'm struggling to comprehend the scope of 'this' in this particular situation. I can easily call each of these functions like: this.startTracking(); from within the time tracker switch object. However, when attempting to execute the code: Dr ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

JavaScript code can be enhanced with HTML comments to improve readability

I have incorporated Google ad into my website using the following code. <script type="text/javascript"><!-- google_ad_client = "pub-"; /*Top 468x15 */ google_ad_slot = ""; google_ad_width = 468; google_ad_height = 15; //--> </script> < ...

The Vue3 counterpart of vNode.computedInstance

I'm currently in the process of upgrading my app from Vue2 to Vue3, but I've hit a roadblock when it comes to dealing with forms. For my form elements, such as FormInput, FormTextArea, and FormCheckbox, I have been using Single File Components ( ...

Top method for refreshing component data from a different component in Nuxt

Being new to Nuxt and Vue, I'm unsure about the best approach for this particular scenario. I am looking to dynamically change the text (such as "Home", "Settings", "Favorites" etc.) within my Header.vue component (which is always fixed at the top of ...

Is it possible for me to generate HTML using JavaScript?

Below is the javascript code I have written, saved as create.js: var stuff = document.querySelector(".stuff"); var item = document.createElement('div'); item.className = 'item'; stuff.appendChild(item); This is the corresponding HT ...

Accessing a subcollection with DocumentSnapshot in Firebase using JS9

Just had a quick question. Is anyone familiar with how to achieve something similar using Firebase JavaScript v9? Essentially, I have a `userDoc` that is a DocumentSnapshot and I need to access a sub-collection with the document snapshot. Here's the c ...