Transforming button hues and passing a property to a subcomponent when clicked using vue.js

Just starting out with vue.js, I am attempting to create a component that functions in the following way:

I have four buttons and when I click on one button, I want to change the colors of all four buttons and send a prop to a child component indicating which button I selected.

This is what I have so far:

<template>
  <v-app>
    <v-toolbar app>
      <v-toolbar-title class="headline text-uppercase">
        <v-flex>
          <v-btn class="mx-2" icon large>
            <v-icon dark @click="reloadPage" >home</v-icon>
          </v-btn>
          <v-btn class="ma-2" :ref="ModelA" :modelProps="modelA" @click="chooseModel(0)" rounded flat text > MODEL A </v-btn>
          <v-btn class="ma-2" :ref="ModelB" :modelProps="modelB" @click="chooseModel(1)" rounded flat text > MODEL B </v-btn>
          <v-btn class="ma-2" :ref="ModelC" :modelProps="modelC" @click="chooseModel(2)" rounded flat text > MODEL C </v-btn>
          <v-btn class="ma-2" :ref="ModelD" :modelProps="modelD" @click="chooseModel(3)" rounded flat text > MODEL D </v-btn>
        </v-flex>
      </v-toolbar-title>
      <v-spacer></v-spacer>
    </v-toolbar>

    <v-content>
      <childComponent/>
    </v-content>
  </v-app>
</template>

<script>
import childComponent from './components/childComponent'

export default {
  name: 'App',
  components: {
    childComponent
  },
  data () {
    return {

    }
  },
  methods: {

    chooseModel:function(model){

      switch(model){
        case 0:
          this.$refs["ModelA"][0].color = "rgb(0, 100, 0)";
          this.$refs["ModelB"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelC"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelD"][0].color = "rgb(100, 0, 0)";
          break;

        case 1:
          this.$refs["ModelA"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelB"][0].color = "rgb(0, 100, 0)";
          this.$refs["ModelC"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelD"][0].color = "rgb(100, 0, 0)";
          break;

        case 3:
          this.$refs["ModelA"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelB"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelC"][0].color = "rgb(0, 100, 0)";
          this.$refs["ModelD"][0].color = "rgb(100, 0, 0)";
          break;

        case 4:
          this.$refs["ModelA"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelB"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelC"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelD"][0].color = "rgb(0, 100, 0)";
          break;
      }
    }

  }
}
</script>

What am I doing wrong here and what can I do to fix it?

Answer №1

Initially, keep in mind that ref is not a standard HTML attribute and therefore cannot be bound. Nevertheless, it is a custom attribute that Vue compiles, allowing you to use it as you would any other attribute.

In addition, accessing $refs['modelA'] will provide you with a reference to the Vue element, as Vue.js also encapsulates native HTML elements.

Lastly, consider storing the selected model in the Vue data and passing it as a prop to the child component.

I have prepared a jsfiddle for your reference.

https://jsfiddle.net/z3qv1dtp/

Furthermore, I suggest utilizing Vue data to store button configurations and passing them as props to each button rather than directly modifying the Vue element.

https://jsfiddle.net/z3qv1dtp/1/

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

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Searching for image labels and substituting the path string

Upon each page load, I am faced with the task of implementing a script that scans through the entire page to identify all image src file paths (<img src="/RayRay/thisisianimage.png">) and then add a specific string onto the file paths so they appear ...

Converting JavaScript code into PHP syntax

I'm curious about code organization. The original code in this snippet is functioning properly: <?php if (isset($_POST['submit'])){ ... ... $invalidField = 2; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD ...

Store JWT as a cookie in Vue JavaScript and ensure it is successfully saved before proceeding

Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home. However, there seems to be an issue with the authentication check on the /home route. When c ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...

Locating the dot character within regular expression challenges

Having difficulty replacing terms like "joe." using a regular expression. Look at the snippet below: var phrases = new Array("joe","sam"); sentence = "joe.id was here as well as sam.id"; for(i = 0; i < phrases.length; i++) { regex = new RegEx ...

Automatically sync textbox width with gridview dimensions

My goal is to dynamically resize a number of textboxes so that they match the width of my gridview's table headers. The gridview will always have the same number of columns, but their widths may vary. However, as shown in the image below, the width va ...

Updating the color of text when clicking on a link using javascript

I am facing an issue where I cannot seem to change the text color using JavaScript. The functionality to show and hide div tags is working perfectly, but changing the color seems to be a challenge. It's worth noting that there are no styles defined fo ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

I am trying to access the id of the button that was selected, but I am unsure of how to retrieve the id from it. The method of using

I am trying to retrieve the id of a selected button for deletion purposes. However, I am unable to get the id from it using 'this.id'. Is there another method I should be using? Below is the code where I create the button: var deleteEmployer= d ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

What is the best way to send data to an API controller using AJAX in an MVC framework?

I am facing an issue with POSTing a string data to the api controller in mvc using ajax. Despite my efforts, the data does not seem to reach the api controller. Here is what I have attempted: This is the JavaScript code I have used: ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

What is the best way to cancel a Promise if it hasn't been resolved yet

Let's consider a situation where I have implemented a search function to make an HTTP call. Each call made can have varying durations, and it is crucial for the system to cancel any previous HTTP requests and only await results from the latest call. ...

Switch language by entering a specific URL (VueJs)

I have successfully integrated localisation using vue-i18n. In my main.js file: import Vue from 'vue' import { i18n } from './plugins/i18n' import Cookie from "vue-cookie"; if (!Cookie.get('locale')) { Cookie.set(' ...

Capturing content from an HTML node and integrating it into VueJS data

<tasks> @foreach ($task as $tasks) <task>{{ $task->name }} [{{ $task->completed }}]</task> @endforeach </tasks> This snippet shows how I display a list of tasks from the database. Here is my Vue component setu ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

Created computed getter and setter for Vue models (also known as "props") using the syntax of Vue Class Component

After exploring the limitations of v-model in Vue 2.x in this Stack Overflow thread, I discovered a way to connect parent and child components using v-model. The solution proposed is as follows: --- ParentTemplate: <Child v-model="formData"> ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...