Changing background image of a container in Vue with dynamic functionality

How can I apply a background image to a div using Vue.js?

I attempted the following method, but it is not working. So far, this is what I have tried: https://i.sstatic.net/wLD7N.png

Currently, the display on my webpage looks like this: https://i.sstatic.net/4ijAD.png

Answer №1

UPDATE: Just a heads up that your method did indeed work. The only thing missing was setting the width and height properties on the div element, causing it not to display on the screen.

See it in action here

If you're looking to dynamically set the backgroundImage using a URL, consider utilizing the following strategy:

[Options API]

<template>
  <div
    :style="{
      backgroundImage: `url(${imageUrl})`,
      width: '100px',
      height: '100px',
    }"
  ></div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      imageUrl:
        "Your image url",
    };
  },
};
</script>

Alternatively, you can opt for the Composition API [script setup]

<script setup>
import { ref } from "vue";

const imageUrl = ref(
  "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
);
</script>

<template>
  <div
    :style="{
      backgroundImage: `url(${imageUrl})`,
      width: '100px',
      height: '100px',
    }"
  ></div>
</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

Creating a dynamic menu in antdesign requires a few simple steps to customize the

I am looking to implement a dynamic menu using antdesign version 4.19.5 Below is the code for a static menu: <Menu selectable selectedKeys={activeKey}> { <Menu.SubMenu title="Main Title 1" > <Menu.Item key={&a ...

Ways to select the initial 10 rows, final 3 rows, and middle 2 rows using Javascript

As a newcomer to Javascript, I have a couple of questions: 1) How can I retrieve the first 10 rows, the last 3 rows, and the 2 rows in the center using the code var firstTable = $('#aaa table').eq(0); 2) Is there a way to create and assign new ...

Retrieve the associative array from the user input by utilizing jQuery

How can I create an associative array from a form containing multiple text inputs using jQuery (or directly in JS)? Here's an example of the form: <form> <input type="text" name="name[13]" value="test 1" /> <input type="text" name="nam ...

What is the best way to layer four images in a 2x2 grid over another image using CSS as the background

I am attempting to place 4 images of the same size on a 5th image defined as the background. Currently, it looks like this: It works perfectly when the height is fixed, but in my case, the height may vary causing this issue: This problem isn't surp ...

Using AJAX to transfer a variable from a range slider to a PHP query

I'm currently trying to pass a JavaScript variable from a range slider to a PHP query. The goal is to have the front-page of my Wordpress theme display all posts tagged with the value selected on the range slider without having to refresh the page. To ...

What is the process for converting an <input type="file> into a base64 string?

Currently, I'm attempting to send an image to my express backend by including the image directly in the post request body. var imgValue = document.getElementById("image").value; Within my post request: body : JSON.stringify({ image:imgValue ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Refresh the redux state within the reactjs component and make use of it in the application

I am in need of assistance with opening a search aid, selecting a value, and retrieving it. After clicking on a button, I activate a search help where I choose data to store. However, I am unsure how to utilize this stored data upon returning. I aim to di ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

"Exploring the method of exporting a function in Vue.js 3 using the Composition API

// Inside File2.vue <script> import { ref, computed } from 'vue'; let example = ref(1); const totalSum = computed(() => { let result = 5 + 5; return result; }); </script> <template> <div class="pa ...

The program failed to run properly because it couldn't find the reference to Chart

I added chart.js to my project using npm with the command: npm install chart.js --save-dev. In the file "resources/assets/js/bootstrap.js", I included it by using: require('chart.js');. After running npm run dev in the console, it compiled succe ...

Session data in ExpressJS is not being stored in the cookie

There are plenty of questions on this topic, but unfortunately, I haven't found any answers that solve my issue. I'm using Chrome with ExpressJS and VueJs 3 to build a simple application where users can "login" and access another page. All I wan ...

Insert an HTML page into a div element

I am having an issue with my angular template. I have a div where I am attempting to load an HTML view file (.html) based on a $watch event, but for some reason, the HTML view is not being loaded into the div. Below is a snippet of my controller code that ...

IE is experiencing performance issues with Jquery's for loop

I have a situation where my Jquery foreach loop is taking significantly longer to execute in IE compared to Chrome. In IE it takes 15.8ms while in Chrome it only takes 1.164ms. I'm looking for suggestions on what changes I can make to improve the perf ...

JavaScript: Add an element to the precise middle of an array

Sorry if this is a repeat question, but I couldn't find the answer despite searching. Let's say there's an array of unknown length and you want to insert items at a specific position, such as the center. How can you achieve this? Here&apos ...

Efficiently transmitting WebSockets events/messages to multiple controllers in AngularJS

Incorporating AngularJs, I created a factory to manage a WebSocket connection effectively. Here is the code: .factory('WebSocketConnection', function () { var service = {}; service.callbacks = []; service.connect = func ...

What is the best way to silence console.log outputs during testing?

There is a utility function that needs to be tested: var util = function(data) { ..... console.log('msg'); .... return true } Here's my test.js file: describe('Testing the util function', function () { it(&ap ...

The value of a variable undergoes a transformation following its insertion into an

During my coding tests, I came across this snippet of code: <script> var newData = {}, graphs = [] for(var j=0; j<2; j++){ newData["name"] = 'value '+ j console.log(newData["name"]); graphs.push(newData); console.log ...

Using Angular to pass parameters to a function

When passing a parameter to the getActiveId function in the ng-click <span class="col ion-ios7-heart-outline center" ng- click="getActiveId({{activeSlide.selected}})"> The value turns to zero in the controller, but it is passed correctly after tes ...

problem with maximum width in Internet Explorer 8

Struggling with a compatibility issue in IE8. Here's my HTML code - Test in any browser and then try in IE8 jsfiddle.net/G2C33/ The desired output should be like this The problem is that the max-width property doesn't work in IE8. Note: Test ...