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.