Utilizing a variable in Vue.js to set the background image in the style template

Is it possible to use a variable within the background-image of a style template?

I am trying to achieve something like the following:

 <script>
  export default {
    name: 'setCss',
    computed: {
    cssVars() {
      var ua = navigator.userAgent.toLowerCase();
      var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
      var path = '';
      if(isAndroid) {
        path = 'img/samsung/';
      } else{
        path = 'img/iphone/';
      }
      return {
        '--bg-path': path,
      }
    }
    }
  };
</script>

and then with this CSS:

    <style scoped>
div {
    background-image: var(--bg-path) + '/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37060401014f03070777054f4c147054">[email protected]</a>';
    background-size: 1366px 400px;
}

@media not all,
not all,
only screen and (max-width: 480px) {
    div {
        background-image: var(--bg-path) + '/480x288.jpg';
        background-size: 480px 288px;
    }
}

</style>

This approach does not seem to work, but I am exploring alternative ways to achieve this. Any suggestions?

Answer №1

To achieve this, you can utilize the concept of class and style binding.

In your scenario, implementing the binding style would resemble the following example. Initially, you will need to bind a style with the computed background image while retaining the remaining styles in your style tag.

<template>
 <div :style="{backgroundImage: computedBgImage}"></div>
</template>
...
computed:{
  computedBgImage() {
      let path;
      if (isAndroid) {
        path = 'img/samsung/';
      } else{
        path = 'img/iphone/';
      }
     return path + '/480x288.jpg'
  }
}
...

If you intend to reuse the same image in various locations, consider creating a class for each image and then binding the class rather than the style, as elaborated in the aforementioned link.

Answer №2

To make this solution effective, all you have to do is pass the calculated property cssVars to the component as a dynamic style attribute like so:

<button :style="cssVars">My button</button>

Check out a live demonstration below:
(In this example, I am directly assigning a value to bgColor, but in reality, it could be passed as a prop to a component)

new Vue({
  el: "#myApp",
  data: {
    bgColor: "green"
  },
  computed: {
    cssVars() {
      return {
        '--bg-color': this.bgColor,
      }
    }
  }
})
button {
  background-color: var(--bg-color);
  padding:10px 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="myApp">
  <button :style="cssVars">My button</button>
</div>

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

What is the best way to merge the values of an array into one variable?

I am facing an issue with handling an array containing objects with two nested nodes, "name" and "title". The array includes product attributes such as "size", "style", "colors", etc. All of these attributes are stored in a single array. My goal is to dyna ...

Utilizing the 'Day' Function in Visual Basic to alter the date and submit a form according to the day of the week

I have been developing a Windows application that utilizes the WebBrowser control to automate form filling based on specific criteria. One challenge I encountered is with dates on certain forms, where different rules apply depending on the day of the week. ...

Can we tap into the algorithm of curveMonotoneX in d3-shape?

I'm currently using curveMonotoneX to draw a line in d3 import React from 'react'; import { line, curveMonotoneX } from 'd3-shape'; export default function GradientLine(props) { const { points } = props; const lineGenerator ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Using prerender.io in conjunction with native Node.js

Currently, I am working on integrating prerender.io into my Angular 1.6.0 application that is being hosted on a Node.js server. The instructions provided in the documentation for setting up the middleware involve using the connect middleware, with a speci ...

Eliminate the ending slash from your Nuxt application

Hello, I am currently working on a Nuxt Application and encountering an issue. After running the npm run build command and starting it with npm start, there seems to be an inconsistency with trailing slashes. During the build, the URL appears without a t ...

Using Confluence to Access a Unique REST API

I've successfully developed and deployed my own webservice using WCF C#. Now, I'm looking to utilize JavaScript to call this service, retrieve data from it, and display it on a chart. Below is the code snippet that I placed within a custom HTML ...

The component encounters a transformation in which prop values shift to undefined

My component seems to be encountering some instability. The value assigned to "this.state.list" from this.props is being immediately set to "undefined". I'm struggling to comprehend why this is happening. Can anyone spot the issue in the code? this.s ...

Error message: Unable to locate module using import instead of require

I am currently in the process of transitioning from using require to using import for all modules within my project. However, I have encountered some challenges with older npm modules that only provide instructions for require. For example, when it comes ...

The image source is visible in Vue.js, but unfortunately, my picture is not showing up

Below is the code and script that I have: <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Tasks</h1> <ul class="tasks_list"> ...

Is it possible to use Selenium WebDriver to automate an HTML5 webpage?

Within my application, there lies an HTML5 webpage. While attempting to inspect it and retrieve IDs/classname locators, I have encountered difficulties in obtaining the necessary locators for specific web elements. I have noticed that many of these elemen ...

Arranging a JSON data structure (varied sequence in Firefox)

Looking to organize a JSON Object based on the key - Chrome maintains the order I need, but Firefox does not. Below is an example of my JSON object: { "media": { "1387185503": { "id_profil": "7256", "photo_profil": "http://www.mupiz.com ...

A scheduled task in Node.js set to run every day at 2 AM

My nodejs cron currently runs every 5 hours using the code below: cron.schedule("0 0 */5 * * *") How can I modify it to run daily at 2 AM instead? Thank you ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

Having issues with Vue.js v-repeat not displaying any content

I have just started learning about vue.js. I attempted to display a simple list, but it is not showing anything. Here is my code: <html> <head> <title>VUE Series</title> <link rel="stylesheet" type="text/css" ...

Enhancing an existing node by adding a new node with jQuery functionalities at the same time

Is it possible to append a node to a parent node while also manipulating the node being added? I initially believed this could be done in one step: //I though this was possible: $('#master').after('<div id="test" style="border:solid 1px ...

Angular implementation of a reactive form including a child component

Upon inspection, I noticed that my father form component is displaying the values of nickName and name, but not the value of age. It seems that {{myFormFather.status}} does not recognize the component child. It's almost as if my child component is inv ...

Ways to perform a jQuery selection beginning with a pre-existing jQuery object

When working with Vanilla JavaScript, you can select an element from the DOM using the following method: let element = document.querySelector('[css selector]'); Once you have the element selected, you can further target elements within it using ...

Adding a function to the window object using Webpack version 5

After transitioning from Webpack 4 to Webpack 5, I encountered an issue with attaching functions to the window object in my index.js file. Previously, I had a function defined on the window object like so: index.js window.someFunction = function (...argum ...

Unable to implement styling to an HTML element using Javascript

Having very limited experience with Javascript, I decided to incorporate a feature on my webpage where the navbar changes size as the user scrolls down. The only way to achieve this was through the use of Javascript. Including the .js file in my HTML docu ...