Guide to Embedding Dynamic Images in HTML Using VUE

I am venturing into the world of VUE for the first time, and I find myself in need of a header component that can display an image based on a string variable. Despite my best efforts to search for tutorials, I have not been able to find a solution.

Header.vue - where the magic happens

<template>
  <header :style="{ ...headerStyle, backgroundImage: 'url(' + imageUrl + ')' }">
    <h1>Place Holder Text: <br> {{ headings.Index }}</h1>
  </header>
</template>

<script>
export default {
  name: 'ImageHeader',
  props: {
    imageUrl: String
  },
  data() {
    return {
      headings: {
        Index: "Home Page",
        About: "About Page"
      },
      scrolled: false,
    };
  },
  computed: {
    headerStyle() {
      return {
        padding: this.scrolled ? '10px' : '50px 10px',
        color: this.scrolled ? 'black' : 'white',
        textAlign: 'center',
        fontWeight: 'bold',
        position: 'fixed',
        top: 0,
        width: '100%',
        height: this.scrolled ? '100px' : '56rem',
        transition: '0.5s',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
        backgroundSize: 'cover',
        margin: 'auto',
        lineHeight: this.scrolled ? '2rem' : '3rem',
        zIndex: 1,
      };
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      this.scrolled = window.scrollY > 50;
    }
  }
};
</script>

App.vue - bringing components together

<template>
  <div>
    <!-- Pass headerImageUrl to the ImageHeader component -->
    <ImageHeader :imageUrl="headerImageUrl"/>
    <SideBar/>
    <!-- Your main content here -->
  </div>
</template>

<script>
import SideBar from './components/SideBar.vue';
import ImageHeader from './components/Header.vue';

export default {
  name: 'App', 
  components: {
    ImageHeader,
    SideBar
  }
}
</script>

index.html - inserting the file path

<body>
     <div id="app" image-url="../src/assets/ImageName.png" </div>
</body>

For security reasons, I have altered some details like image names and text content. Additionally, only the necessary div element has been included in the html file. Working within the default vue directory template.

My closest attempt involved hardcoding a file path to a png/jpeg file hosted online in App.vue, but this proved to be a static solution unfit for multiple pages using the App component.

Answer №1

It seems that the issue lies in index.html not supporting props being passed. Instead, try passing your image string directly into ImageHeader:

<ImageHeader :imageUrl="../src/assets/ImageName.png"/>

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

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Updating the src of an iframe and adding an onclick event to a link using JavaScript

Looking to design a page that accommodates both login and sign up functionalities by dynamically updating the src of an iframe. In the navigation bar, there is: <li id="change"><a onclick="sign()">Sign up</a></li> And within the ...

Changing an array with VueJS

I have encountered a strange issue while using vuex to store state. It appears that there is a problem with changing the id of one of my objects. During my action, I am fetching data about a specific note saveNote({commit}, noteInfo) { var for ...

Add drop caps to every individual word within a hyperlink

Is there a way to recreate the menu effect similar to using CSS fonts and drop caps for each word? I'm aware of the CSS code: p.introduction:first-letter { font-size : 300%; } that enlarges the first character of the first word, but I want this ef ...

What is the reason for the background image not appearing while utilizing a bootstrap template designed for it?

I recently started working on an asp.net application and decided to integrate a pre-made bootstrap template for the frontend. After some searching, I came across this one. The original site showcasing the template looked really appealing with a background ...

No styles are appearing on a specific element after running a specific jQuery function on that element within a Vue page

I recently integrated JQuery-AsRange (https://github.com/thecreation/jquery-asRange) into my vue.js project. Everything functions as expected within the .vue page, however, I am facing an issue with css styling not being applied. The css styles should be ...

Javascript continues to conceal my web background without my permission

After loading my webpage, I click on a link and the expected javascript runs as planned. However, once it completes and presents the results, the page goes blank to a white screen displaying only the outcomes. My goal is to have these results showcased o ...

A guide on how to alternate between ng-hide and ng-show using separate controllers by utilizing a shared factory toggle state instance

Using Angular 1.x, I have implemented two controllers where I want to display controller_2 if controller_1 is hidden. To achieve this, I am utilizing a factory method. Here is the snippet of my HTML code:- <div ng-controller="controller_1 as c1" ng- ...

Establish a predetermined selection for a radio button and its associated checkbox option

I am working on a React material UI group input field that is mapping a dataset. The result consists of one radio button and one checkbox performing the same action. Initially, I attempted to set the state to establish one data item as default. While I fol ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...

push one element to fit in between two adjacent elements

Is there a way to make my responsive webpage ensure that the full-screen element appears between sibling elements when viewed on mobile devices? Check it out on desktop or on mobile here. I have three (div) elements: two in one row and another in a separa ...

When executed on the node REPL, lodash.sortBy will update the lodash value

When I access the node REPL, the following happens: > _ = require('lodash'); > // it displays the whole lodash object > _.sortBy(['1234', '123'], function (element) { return element.length; }); > [ '123&apos ...

Utilizing JavaScript to transition a grayscale thumbnail image to vibrant color

I am a beginner in the world of web development and I have no idea how to begin coding a JavaScript function that will smoothly transition a grayscale thumbnail image into a color thumbnail image when the user hovers their mouse over it, and then back to g ...

What steps do I need to take to get a website up and running with the index.html

After successfully hosting my website, I encountered an issue where it opens the index of the website (a list of files added via FTP) instead of the Index.html page. Can you advise on how to resolve this? Your assistance is greatly appreciated. ...

Guide for invoking a servlet via a navigation bar hyperlink and implementing a jQuery feature for smooth scrolling upon clicking

Is there a way to call a servlet from a navigation bar href link and at the same time trigger a jQuery function for smooth scrolling down? I attempted to call the servlet using an onclick href link, it successfully calls the servlet but does not trigger t ...

The issue of CSS transitions flickering in Internet Explorer

Can someone help me troubleshoot an issue with this code in Internet Explorer? CSS: .nav-fillpath a { width: 100px; height: 100px; position: absolute; display: block; bottom: 0%; left:0; right:0; color: #3e3e3e; margin ...

Issue with implementing jQuery tab functionality

I'm just starting to learn JS, HTML, and CSS, and I could use some guidance on setting up jQuery tabs. Currently, I'm encountering an error that says "Uncaught TypeError: $(...).tabs is not a function". Any help would be greatly appreciated. Than ...

Retrieve the texture's color based on the UV coordinates

Currently, I'm working with version 73 of V. I am dealing with UV coordinates obtained from the intersection of a raycaster and a texture of an object. Is there a way to extract the color (RGB or RGBA) of the used texture at these specific UV coordina ...

Unable to show message upon form submission with ajax

I'm attempting to use AJAX to submit a form in CodeIgniter. The form values are being saved in the database, but the response set in the controller isn't displaying in the console.log or alert within the AJAX code. Form Code <form class=" ...

Encountering a problem during the conversion of HTML to JSON

I am facing an issue with the content of a specific div on my webpage. <div id="hidLocsJsonForAutoComplete" style="display:none;">[{"id":1,"desc":"Amazon","name":"amazon"},{"id":2,"desc":"Apple Bees","name":"applebees"},{"id":3,"desc":"Babys r Us"," ...