VueJs and the behavior of styling elements with inline CSS

Within my HTML, there is an <input> element that has the ability to change the background color of a <p> through an inline style. I conducted an experiment using two different methods to apply the style, and I encountered a peculiar behavior: when I type "blue," both paragraphs turn blue. However, if I then press the backspace key, Paragraph 2 remains blue until the input field is either empty or contains another valid color (e.g., backspacing from "yellowgreen" to "yellow"), which strikes me as odd. On the other hand, Paragraph 1 behaves as expected: if the input is not a valid color, it remains unstyled.

I suspect that this behavior is related to how Vue transforms a "style object" into actual CSS styles. Can someone explain how this process works? (Just to clarify: I am a complete beginner to Vue.js)

HTML:

<section id="assignment">
  <input type="text" v-model="bgc" />
  <p :style="bgcInlineStyle">Paragraph 1</p>
  <p :style="{backgroundColor: bgc}">Paragraph 2</p>
</section>

JS:

const app = Vue.createApp({
  data() {
    return {
      bgc: "",
    };
  },
  computed: {
    bgcInlineStyle() {
      return `background-color:${this.bgc};`;
    },
  },
});

app.mount("#assignment");

Answer №1

Within the first paragraph, you are assigning a string value to the style attribute.

In the second paragraph, an object value is being assigned to the style attribute.

When dealing with string values, the browser will interpret the style attribute and make immediate updates to the display. If an invalid property or value is included, CSS will simply disregard it.

For object values, Vue will dynamically adjust the style properties based on the key-value pairs within the object. If an invalid value is encountered, Vue will skip that particular property and prevent it from being updated through JavaScript. This is the reason why the background color remains blue.

Vue manages style objects using JavaScript, as shown in the following example:

document.querySelector("p").style.backgroundColor = "blue";
document.querySelector("p").style.backgroundColor = "blu"; // this will be ignored and will not reset the value to blank

Answer №2

Computed properties store their values based on the reactive dependencies they have.

Check out more on this topic here: Computed Property and Caching

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

Click on the print icon in the modal window

I have been working on a receipt generator for a client. The client can add payment receipts using the "Add" button, and upon submission, they have the option to convert it to PDF or print it. However, there seems to be an issue with printing as the text f ...

Adjust the field's color depending on the outcome displayed within

I'm trying to implement a feature where the field value changes to green when "OK" is selected and red when "NOK" is chosen. I have written the following JavaScript code but it's not working as expected - the colors change before clicking submit, ...

Vue-Auth: The property 'beforeEach' is not defined and cannot be read

I'm currently working on integrating my VueJS SPA with a Laravel API. I came across a plugin called vue-auth that seems to be perfect for handling role-based authentication: Here's the Github link: https://github.com/websanova/vue-auth And her ...

Achieve a stylish layout by displaying three cards per row using Vue.js and Bootstrap 4

I'm facing an issue with my code where I am trying to display Bootstrap cards in rows of three, but the layout is not rendering correctly. It starts with one card, then two, and eventually adds a new column, resulting in some empty spaces with offsets ...

Customizing BootstrapVue styles by overriding default Bootstrap styles: encountering an error due to undefined variable

I recently set up a new Vue application and integrated Bootstrap-Vue for styling, but I'm encountering difficulties when trying to customize Bootstrap's default style. Error message: [sass] Undefined variable. 11 │ $b-custom-control-indicator- ...

strange issue encountered while utilizing JavaScript's async/await syntax

Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend. // Here is the structure of the API response { info: { // details omitted }, results: [ {//random user data} ] } // This snippet ...

Creating dynamic CSS backgrounds that scroll horizontally

Styling with CSS #container { min-width: 800px; max-width: 1000px; height: 100%; margin: 0 auto; text-align: left; } #left-section { height: 100%; position: relative; float: left; ...

The fixed position div remains stationary as the page scrolls

Below, I am attempting to fix the position of the 'inner-navigation' div within the 'compare-display' box by making it absolutely positioned. However, when scrolling, the 'inner-navigation' div is not staying fixed. How can I ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

How do I ensure that in Vue.js, the select element always has the first option selected even when other options are dynamically shown or hidden?

In my Vue app, I have a select element that dynamically shows or hides options based on the user's previous selections. For example: <select id='animal' v-model='values.animal.selected'> <option value='cat' ...

What could be causing issues with my CSS/HTML on Internet Explorer, including version 9?

Utilizing modernizer and html5boilerplate's CSS, I have encountered challenges in designing and debugging for Internet Explorer. It seems that my reliance on FireBug has hindered my progress. Can someone please review my work-in-progress at and provi ...

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...

The visibility of overflow-y does not seem to be working properly when overflow-x is

https://i.sstatic.net/hihjC.png .iati-list-table { overflow-x: auto; overflow-y: visible; } When I apply overflow-visible, a scroll bar appears. But when I use overflowy-hidden, the tooltip is cropped. How can I set it so that overflow x is auto a ...

I am able to successfully make a REST API call using curl from the terminal, but when trying to access the same endpoint from my Vue application

If I run a curl command like this: curl --request POST \ --url http://localhost:3600/users \ --header 'content-type: application/json' \ --header 'user-agent: vscode-restclient' \ --data '{"email&qu ...

Issue with loading HTML file correctly in Django

I have been attempting to integrate my Django app with an admin dashboard from a repository on GitHub. After successfully logging in, the app redirects to the dashboard, but only the HTML part loads and none of the fancy features are visible on the dashboa ...

Is it possible to customize bootstrap classes for a unique bootstrap css design?

In my MVC4 project, I faced a situation where I had a global.css class with some classes that conflicted with Bootstrap after adding it. To resolve this, I created a new file called bootstrap_migration.css. In this file, I prefixed the Bootstrap classes wi ...

Get rid of the dashed outline surrounding the selected button

One of my divs has a button inside that, when clicked, creates an outline around it. Here is what it looks like: https://i.sstatic.net/pEr53.png **Code: ** .slide-arrow { color: #fff; background-color: #9E9997; border: none; padding: 16px 10px ...

Guide to developing a Microsoft Teams tab application using the VueJS framework

I'm in the process of configuring a teams app using VueJS, as my project is based on it. My attempt to create a teams app with Visual Studio and integrate VueJS into it has not been successful. The components don't work properly and imports are ...

Struggling to make the bootstrap navigation bar function properly

I've been experimenting with replicating the basic framework to learn more about responsive web design using bootstrap. However, I've only been able to get certain parts to function correctly. For instance, I can use the "btn" class without any i ...

Guide on converting the <br> tag within a string to an HTML tag in VUE.js

When working with Vue.js, I often use {{}} to display my data on the HTML page. However, I recently encountered a situation where my data includes a string with tags that I would like to be rendered as actual HTML tags when displayed. data(){ return ...