What is the best way to choose a tag from an app within components or views?

In my main component file, I added a color picker input in the navigation section to change the background color of the application. This works fine as the body tag can be accessed easily within the DOM.

Furthermore, I store the selected color in local storage so that it persists even after refreshing the page.

However, when attempting to add another color picker to modify the color of specific cards within a component or view, I encounter difficulty in targeting the relevant element.

<template>
<div id="app">
    <nav>
          ...
        <div class="color">
            <input type="color" id="colorInputCards">
            <font-awesome-icon input type="button" id="colorButtonCards" :icon="['fas', 'paintbrush']" @click="changeCardColor()" />
        </div>
    </nav>
    <router-view/>
</div>
</template>

<script>
export default {
    components: {},
    methods:{
        changeCardColor() {
            let cardColor = document.getElementById("colorInputCards").value;
            console.log(cardColor);
        }
    },
}

</script>

I have tried:

  • Using querySelector
  • Adding a ref attribute to the desired element and accessing it through
    this.$refs."refname".style.backgroundColor
    , but without success.

Answer №1

To implement two-way data binding and a watcher in Vue, you can use v-model and follow this example: (live example)

<script>
export default {
    data () {
      return {
        colorInput: undefined
      }
    },
    watch: {
      colorInput(color) {
        document.body.style.backgroundColor = color
        localStorage.setItem("background", color)
      },
    },
    created() {
      this.colorInput = localStorage.getItem("background")
    }
}
</script>

<template>
  <input type="color" v-model="colorInput">
</template>

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

Requirements detailed in package.json

Suppose we have a client-side application (such as an Ember app). We define the package.json file for our application with its dependencies listed. { name: "my-app", dependencies: { "dep1" : "1.0.0" }, devDependencies: { ...

Convert npm folder structure to JSON format

I am attempting to utilize Dree to retrieve the folder structure as a JSON object. After following this link, I have successfully installed the package: https://www.npmjs.com/package/dree To test it out, I have provided the path to my components folder w ...

Combining user input data using JavaScript and Vue.js

I am working on a form using Vue.js and I want to combine the data from the input fields upon submission. I have been struggling to achieve this and created a jsfiddle to showcase my attempt. In my form, I have three Vue components for each of the input f ...

Develop a seamless user experience by creating dynamic forms using Jquery, PHP, and

I have been attempting to create a simple contact form using jQuery, AJAX, and PHP without refreshing the page. Everything seems to be working smoothly except for event.preventDefault(); Here are my files: Contact_engine.php <?php $name = $_POST ...

Issue on Heroku with Discord.js displaying a "Service Unavailable" message

Encountered a strange error while trying to launch my discord bot on heroku. Previously, I implemented a command handler for the bot to organize commands in separate files but faced multiple code errors. With the help of a member from this community, all e ...

Include a search bar for vue2-leaflet package

Does anyone have samples of code for adding a search bar to a vue2-leaflet map? I tried using the vue2-leaflet-geosearch package but encountered issues. Any alternatives or solutions would be greatly appreciated. Thank you in advance. <template> ...

Is there a way to stop the execution of myFunc after it has been performed 5 times using clearInterval?

This code is designed to notify online shoppers that they need to choose a color from a dropdown menu before adding an item to their shopping cart. If no color is selected, the text will blink to alert them. How can I modify this code so that the blinking ...

Can a cancel button be added to a mobile keyboard for easier use?

Looking to streamline the mobile UI for my Vue-built SPA by removing unnecessary buttons. Encountering an issue with form submission on mobile keyboards triggering unwanted listeners. Is there a way to introduce a cancel button for forms on mobile? ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...

What is the best way to display a string state value in a React component?

I need assistance with displaying a state value that is in string format. Despite my efforts, I have not been successful in finding a solution and am feeling quite frustrated. Can anyone provide some guidance? ...

Cookies are mysteriously invisible in the developer console of Safari/Chrome when using the Set-Cookie Header, yet they miraculously appear in server logs

Storing cookies for my web app using the 'Set-Cookie' header response from my python backend has been a challenge. https://i.stack.imgur.com/XMx35.png An ajax call on the client-end to the function is where I run into issues: https://i.stack.im ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

Is there a method to make this package compatible with Angular version 16?

I recently integrated the ngx-hotjar package version 11.0.0 into my Angular 10 project with success. However, when trying to use it in a new Angular 16 project, I encountered the following error during ng serve: Error: src/app/app.module.ts:275:12 - error ...

The PHP file on the server is missing the mandatory "event" parameter for the EventSource

Explaining this issue was a bit of a challenge. I've set up a Javascript EventSource object with some customized event handlers like so: var source = new EventSource('updates.php'); source.addEventListener('add', addHandler, fals ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

I desire to share the JSON information and receive the corresponding response data

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> ...