如何根据路由切换Vue组件中的数据?
Solution for Dynamic Portfolio Images Based on Vue Route
Hey there! Let's get your portfolio loading the correct images when switching between Aircraft and Animals routes. Here's how to adjust your code to make that happen:
Key Issues in Your Current Code
Right now, your subitem component has a hardcoded list of Aircraft images—no logic to swap them out when the route changes to /Portfolio/Animals. We'll fix this by tying the image data directly to the route parameter (:id in your route definition).
Modified Code with Dynamic Image Loading
Vue.component('subitem', { props: ['photo'], template: ` <a :href="photo.img"> <img :src="photo.img" width="100%" height="auto"> </a> ` }); const subitem = { data() { return { // 新增:维护分类与对应图片列表的映射关系 categoryImageMap: { 'Aircraft': [ {img: 'Images/Portfolio/Aircraft/image1.jpg'}, {img: 'Images/Portfolio/Aircraft/image2.jpg'}, // 修正了原代码重复的image1路径 {img: 'Images/Portfolio/Aircraft/image3.jpg'} ], 'Animals': [ {img: 'Images/Portfolio/Animals/animal1.jpg'}, {img: 'Images/Portfolio/Animals/animal2.jpg'}, {img: 'Images/Portfolio/Animals/animal3.jpg'} ] } } }, // 新增:计算属性,根据路由参数动态返回对应分类的图片 computed: { photos() { // 从路由获取当前分类,默认回退到Aircraft避免参数无效 const currentCategory = this.$route.params.id || 'Aircraft'; // 返回对应分类的图片列表,无匹配则返回空数组 return this.categoryImageMap[currentCategory] || []; } }, template: ` <div> <breadcrumbs></breadcrumbs> <info></info> <div class="portfolio" id="portfolio" data-featherlight-gallery data-featherlight-filter="a:not(.all)"> <!-- 修改:修正v-for的key值,避免重复key报错 --> <subitem v-for="(photo, index) in photos" :key="index" v-bind:photo="photo"> </subitem> </div> </div> ` }; const router = new VueRouter({ mode: 'history', routes: [ { path: '/Portfolio/:id', component: subitem }, { path: '/Portfolio', component: item } ] });
What Changed & Why?
- Added
categoryImageMap: This lookup object links each category name (matching your route's:idvalue) to its specific image list. It keeps your image data organized and makes adding new categories later super easy. - Created a
photosComputed Property: Computed properties automatically update when their dependencies change—here, when the route's:idparameter switches, it instantly pulls the right image list for the new category. We added a fallback to 'Aircraft' to handle invalid or missing parameters. - Fixed the
v-forKey: Your original key usedsubitem.photowhich was incorrect (each item's image path is stored inimg). Usingindexis a simple fix here, or you could use theimgpath itself since it's unique.
Bonus Tips
- If you add more categories down the line, just add a new entry to
categoryImageMap—no need to tweak the rest of the component logic. - If your images follow a strict naming pattern (like
image1.jpg,image2.jpgfor every category), you could generate paths dynamically instead of listing them all, but the lookup map is more flexible for unique image names.
内容的提问来源于stack exchange,提问作者Joe Bailey
相关产品推荐
相关产品推荐

