Adjusting data in Vue according to a method's parameter

I am new to Vue and I am facing a simple issue that I can't seem to resolve. My goal is to have a mounted event in which a method is called with a specific parameter to change the "show" value of an element. Here is my code:

export default {
    data(){
        return {
            one: false,
        }
    },
    methods: {
        show: function(el) {
            this.el = true;
        }
    },
    mounted(){
        this.show(this.one)
    }
}

I intend for "el" to act as a generic placeholder for any "data" name passed into the method. In the future, I may have more options like "two", "three", and "four". The purpose of the "show" method is to toggle the value from false to true based on the reference provided.

However, when accessing the show method, I encounter the error "'el' is defined but never used." The only workaround I've found involves using an if statement such as "if this.one === el {...}", but I believe there should be a better solution. Any assistance would be greatly appreciated.

Answer №1

If you need to perform a similar task, consider the following approach:

export default {
  data(){
    return {
      first: false,
      second: false 
    }
  },
  methods: {
    performAction(element) {
      this[element] = true;
    }
  },
  mounted(){
     //This method can also be used with Vue props!
    this.performAction('first')
    this.performAction('second')
  }
}

However, for more complex functions, it is advisable to create a separate component. This aligns with the recommended Vue.js practices.

Answer №2

Creating a new Vue instance with defined data, computed properties, and methods to show/hide div elements based on conditions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d9d5c6dfd1d0f4849a879a82">[email protected]</a>"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1112191c0e153d49534c4b534d">[email protected]</a>"></script>
<div id="editor">

<div id="div1" v-if="el===true && item =='div-1'" class="show">
div1 displayed
</div>
<div id="div-2" v-if="el===true && item =='div-2'" class="show">
div2 displayed
</div>
<button v-on:click="show(true, 'div-1')">show div1</button>
<button v-on:click="show(false, 'div-1')">hide div1</button>

<button v-on:click="show(true, 'div-2')">show div2</button>
<button v-on:click="show(false, 'div-2')">hide div2</button>
</div>

Answer №3

const myComponent = {
    data(){
        return {
            isOpen: false,
        }
    },
    methods: {
        toggleModal(status) {
            this.isOpen = status;
        }
    },
    mounted() {
        this.toggleModal(this.isOpen)
    }
}

To implement the functionality, utilize the provided code snippet above.

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

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

Eliminate redundant words in a map using React

{this.state.filterDataRows && this.state.filterDataRows.map((row, index) => { return row.cells.filter( val => { if(val.text.toLowerCase().includes(this.state.columnFilter.toLowerCase())){ return true } ...

Changing the color gradient of a range column chart in ApexCharts

Currently, I am working on a project where I am trying to incorporate a waterfall chart using ApexCharts. Unfortunately, the Waterfall chart is not readily available with ApexCharts, so I am experimenting with modifying the range column chart into a Waterf ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

Discovering the bound ASP.NET AJAX event handlers for a specific DOM element

I am currently working on customizing a pre-existing ASP.NET 3.5 AJAX web application, specifically SharePoint 2010. Unfortunately, I do not have the ability to modify the source code. My task involves adding a click event handler to act as the first even ...

Open a submenu when clicking on an input field and automatically close it when the focus is lost

Is there an easier way to create a submenu that opens on input click and closes when losing focus using jQuery? Right now, I have achieved this functionality with the following code: $(document).mouseup(function (e){ var container = $(".container"); ...

Transitioning to TypeScript: Why won't my function get identified?

I am in the process of transitioning a functional JavaScript project to TypeScript. The project incorporates nightwatch.js Below is my primary test class: declare function require(path: string): any; import * as dotenv from "dotenv"; import signinPage = ...

A guide to creating an or statement in MongoDB using the find method in Mongoose

I'm seeking a solution to check for bookings within a specified time range in MongoDB using Mongoose. I am unsure of how to incorporate the OR condition into my query. Below is the current code snippet: const appoinments = await Appointment.find({ ...

How can I refresh an HTML element when a value in a multi-dimensional array changes?

I'm facing an issue with a v-btn component that gets its content from values deep inside a multi-dimensional array. <div v-for="student in students"> <v-btn disabled v-for="tag in student.tags">{{tag}}</v-btn> </div> In ...

What is the best way to handle passing the "img" object to an onload event handler in ReactJS JSX?

I am currently working on an img element that I want to be able to listen for the onLoad event. However, I also need access to the image object itself in order to check properties like width and height. Since these images are generated dynamically, I won&a ...

What is the best way to allocate inner JSON to an object within a promise?

Exploring the Angular2 tutorial "Tour of Heroes" showcases how to handle JSON data within a promise. But what if the JSON structure is more complex? JSON: let complexMessage = [{ "heroes":[ {id: 11, name: 'Mr. Nice'}, {id: 12, ...

Unable to load the threejs module

I am still learning about threejs and have mostly worked on projects using a dev server (vite) locally. This setup limited me to accessing my projects only from the browser on my computer. Here is how I typically include my files in these projects: <bod ...

Leverage the power of Webpack to make Vue available globally

Currently, I am dealing with a situation in a legacy Rails application that has undergone some migration to integrate Webpacker and Vue. Additionally, we are utilizing a legacy script loaded through a CDN that also requires Vue. However, instead of bundlin ...

Converting special characters from a CSV file into JavaScript

I am working with a ".csv" file and using jQuery.get() to retrieve it. $.get("data.csv", function(data) { console.log(data) }, "text") My challenge arises when trying to save the file as an xml. The issue lies in the encoding of the text. Input: Å ...

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

Listening attentively for sliding events in Vuetify Vue, capturing the value only when necessary

After installing the vuetify plugin for my project to utilize a colorpicker plugin, I encountered specific requirements that necessitated manual adjustments to the function and style of the plugin. https://i.sstatic.net/8bM8L.png The current plugin inclu ...

The action to set the 'isRightSidebarExpanded' property is trying to target an undefined element

I'm currently in the process of adapting a template for use with nuxt.js This specific attribute is causing an error to occur When trying to set 'isRightSidebarExpanded', I receive the following error: Cannot set properties of undefined ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Is it necessary to update the expiration time by refreshing the cookie with every request/response in Node.js?

Enhanced Authentication Within my Node.js backend powered by Express.js, I implement user authentication using JWT stored in an HttpOnly cookie that expires after a designated number of hours (N). A middleware verifies the validity of the JWT and either p ...