我有一个Banner组件。当我导航到其他路线时,我想在那里更改图像。就像为单独的内部页面使用不同的横幅图像一样。我想将该横幅组件用作其他组件中的嵌套组件。
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav m-auto custom-nav">
<li class="nav-item">
<router-link to="/">home</router-link>
</li>
<li class="nav-item">
<router-link to="/about-Us">about us</router-link>
</li>
<li class="nav-item">
<router-link to="/characters">characters</router-link>
</li>
<li class="nav-item">
<router-link to="/our-comics">comics</router-link>
</li>
</ul>
</div>
横幅组件
<template>
<section class="banner-outer">
<img src="../assets/banner.jpg" alt class="img-fluid" />
<div class="banner-content-outer">
<div class="container">
<div class="banner-content-inner">
<h1>EXPLORE THE UNIVERSE</h1>
<h5>Dive into the dazzling domain of all the classic characters you love ...</h5>
</div>
</div>
</div>
</section>
</template>
关于我们组件,请与我们联系组件
<template>
<banner />
</template>
答案 0 :(得分:1)
在每个页面组件中,将图像作为 prop
传递到横幅组件...
<template>
<banner which-banner="//path/to/img.png"></banner>
<div>component page content...</div>
</template>
在横幅组件中...
<script>
...
{
props: ['whichBanner']
}
..
</script>
<template>
<section class="banner-outer">
<img :src="whichBanner" alt class="img-fluid" />
<div class="banner-content-outer">
<div class="container">
<div class="banner-content-inner">
...
</div>
</div>
</div>
</section>
</template>
答案 1 :(得分:0)
您可以使用beforeEach
:
router.beforeEach((to, from, next) => {
// check current route to set the valid image
// in vuex or localstorage or even a global window variable
if(to === 'about-us') {
// using global variable
window.bannerImagePath = 'path/to/about-us/banner.png';
// localstorage
localStorage.setItem('bannerImagePath', 'path/to/about-us/banner.png');
} else if( ... ) { ... }
return next();
});
然后您可以在BannerComponent
内的mounted()
中获得它,或为此设置一个method
示例:
<img :src="getCurrentBannerImage()" alt class="img-fluid" />
methods: {
getCurrentBannerImage() {
// global variable example
return require(window.bannerImagePath) // or any storage you choose
// localStorage
let _item = localStorage.getItem('bannerImagePath');
return require(_item) // or any storage you choose
}
},