Updating the background of the page dynamically using VueJS

Currently, I am working on developing a form creation feature that allows users to select a background color for their forms. This selection would then reflect as the background color of the body tag. Users are given several color options to choose from, and their selection should automatically change the background color.

The project is being implemented using Laravel and Vue technologies. However, I am facing challenges in dynamically updating the background color based on user selections. I have explored different methods but haven't had much success so far.

One approach I tried was creating a beforeCreate hook to modify the body's background color:

beforeCreate() {
        this.color = 'bc-header-red';
        document.body.className = this.color;
    },

Unfortunately, this method did not allow me to update the background color as desired, even with an update() hook. Another option I came across is similar to an implementation found in this jsfiddle link. Essentially, it involves binding the style of the body tag to a certain value. However, a challenge I faced here is that the body tag resides in my Laravel blade file rather than the Vue JS file. Is there a way to move it?

I am open to exploring other possible implementations or solutions to achieve the desired functionality. Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

If you want to change the background color dynamically in your Vue application, you can utilize the $emit method:

Within your Vue component, create a method that will handle the color selection process as shown below:

handleColorChoice() {
    this.color = this.colorChosen;
    document.body.className = this.color;
}

To make it emit the chosen color, update the method like this:

handleColorChoice() {
    this.color = this.colorChosen;
    document.body.className = this.color;
    this.$root.$emit('body-background-color', this.colorChosen);
}

Now, you have defined an event, which you can listen to in your main component:

In your main component, add the following code inside the mounted method:

mounted() {
    this.$root.$on('body-background-color', function(color) {
        //handle the background color change here  
    });
}

I hope this explanation is clear and helpful for you.

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

Using LocalStorage within the Selenium Webdriver

Do LocalStorage stores differ between a regular browser and Selenium Browser? I've noticed that when I create an item on Selenium Chrome, it disappears after I close the browser. Is this supposed to happen? Additionally, I am unable to read the localS ...

Having trouble with loading textures in Three.js?

I'm facing an issue while trying to apply a texture to my mesh using three.js. Instead of the expected loaded texture, I am just seeing a plain black object. I followed the examples provided in the three.js documentation ( - Example) and also tried va ...

Creating a static HTML page using Flask and incorporating redirects

I have a web application built using Flask that processes a URL, performs some operations, and then redirects the user to another URL. I am looking for a way to display a simple "please wait" message in a static HTML page while the processing is happenin ...

Working with Ember.js to manage relationships using a select element (dropdown) for create/edit operations

I'm trying to establish a relationship through a dropdown in my Ember application. Here is my Books model: import DS from 'ember-data'; export default DS.Model.extend({ // Relationships author: DS.belongsTo('author'), name ...

Executing JavaScript functions with Python and BeautifulSoup

My current project involves web scraping to extract data from a website. While I can successfully retrieve information present in the DOM, I am facing a challenge with data that is rendered through a JavaScript onClick function. One potential solution is ...

Understanding the `DOMNodeInserted` event listener can be incredibly useful for pinpointing changes within Iframe contents

On my website, there is an iframe that loads content and I am trying to find the element that comes after it has finished loading. This is the function I used: $("body").on("DOMNodeInserted", ".issueContentIframe", function() { $(this).css('border& ...

The ios browser environment is unable to retrieve the value during vuejs development

When using vuejs components to create a countdown component, everything seems normal in the pc and Android environments. However, in the iOS environment, there seems to be an issue with obtaining the real count calculation as it returns NaN. <templ ...

Deciding whether to implement Vuex in NUXT: A series of queries

I really appreciate NUXT framework, but it presents some challenges for me because we lack deep understanding of its underlying implementation and operational principles. I have a few questions regarding these concerns that I hope you can provide some guid ...

When defining multiple types for props in Vue, the default behavior for Boolean type props is not preserved

Imagine you have a component called MyComponent with a prop named myProp declared as: props: { myProp: Boolean } By simply using <MyComponent myProp/>, the default behavior would set myProp to true. However, this simplicity is lost when there ...

Unable to alter Mui input label color upon focus using theme.ts

In my next.js app, I'm facing an issue with changing the color of the label in a Material UI input field using Mui. Despite updating the theme.ts file to change the border bottom color and label color, only the border bottom color is being applied. T ...

Display the JSON array outcome using Laravel 5.4

After downloading a JSON array result from Instagram, I am looking to extract the image URLs in order to display the posts. How can I retrieve all of the image URLs? "pagination": {}, "data": [ { "id": "1501575131271622723_414010731", "user": { ...

Combining lodash flow with multiple arguments

In my code, I have two functions that will be added in a lodash flow: function normalizeFields(fields) { return _.mapValues( fields, function(value) { return { 'content': value }; }); } function mergeModelAndFields(model, normal ...

Styling your website's navigation with CSS

I'm looking to create a navigation menu using HTML ul li that displays drop down items in a similar way to www.microsoft.com. For example, when you click on 'Products' on the Microsoft website, it shows a list of products in one dropdown win ...

Is there a way to reverse the selection of a row in a kendoui grid?

How can I invert a current selection in a KendoUI grid that is set to "multiple" selection mode? ...

The performance of Google Maps API is compromised by a high number of markers,

Currently, I am facing a challenge with loading approximately 600 Google Map markers on page load using the addMarker function. The loading time for the page is quite long. Is there any way to optimize the loading speed while still utilizing the addMarke ...

Inactive subpages are not activating

My website has add, view, and edit pages. When I click on the add or view pages, both the page and its parent become active. However, when I click on the edit page from the view page, only the page becomes active but not its parent. Here is an example of m ...

Is the utilization of javascript functions intertwined with the specific version of bootstrap being used?

I wrote a function that breaks down each letter in a paragraph to create a typing effect. However, after taking a break for a few days, I noticed that the effect was now the opposite – the letters were disappearing. To solve this, I decided to animate ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

comparison of declarative loop and imperative loop

In my journey to transition from an imperative programming style to a declarative one, I've encountered a challenge related to performance when dealing with loops. Specifically, I have a set of original DATA that I need to manipulate in order to achie ...

Is it possible to utilize two distinct data sources for the primary chart and dataZoom feature within Apache ECharts?

Working with Apache ECharts requires using two different data sources: one for the main chart and the other for the dataZoom preview. To reduce data sent to clients, I have decreased the resolution over longer time periods. However, when a user zooms in o ...