根据路线更改Vue组件中的数据

时间:2019-11-19 14:12:27

标签: vue.js vuejs2 vue-component vue-router

我需要根据路线更改Vue组件中的数据。例如,当页面“飞机”被加载时,我希望数据包含飞机图像。如果随后加载了动物页面,那么我希望数据包含动物图像。

可以在此处查看该网站:https://test.joebaileyphotography.com/Portfolio

Vue.component('subitem', {
      props: ['photo'],
      template: `
        <a :href="photo.img">
            <img :src="photo.img" width="100%" height="auto">
        </a>
      `
    });    
const subitem = {
        data() {
            return { 
                photos: [
                    {img: 'Images/Portfolio/Aircraft/image1.jpg'},
                    {img: 'Images/Portfolio/Aircraft/image1.jpg'},
                    {img: 'Images/Portfolio/Aircraft/image1.jpg'}
                ],
            }
        },
        template: `
            <div>
            <breadcrumbs></breadcrumbs>
            <info></info>
            <div class="portfolio" id="portfolio" data-featherlight-gallery data-featherlight-filter="a:not(.all)">
            <subitem
                v-for="subitem in photos"
                :key="subitem.photo"
                v-bind:photo="subitem">
            </subitem>
            </div>
            </div>
      `
    };
const router = new VueRouter({
        mode: 'history',
        routes: [
            { path: '/Portfolio/:id', component: subitem },
            { path: '/Portfolio', component: item }
        ]
    });

1 个答案:

答案 0 :(得分:1)

您可以使用Vue路由器的功能Dynamic Route Matching,并在组件中使用:id来访问this.$route.params.id

或者您可以pass route parameters as props。 只需将路线定义更改为{ path: '/Portfolio/:id', component: subitem, props: true },,然后在id组件中定义subitem prop

您可以使用传递的id来过滤照片阵列,例如:

computed: {
  getPhotosById(id) {
    return this.photos.filter(photo => photo.igm.startsWith(`Images/Portfolio/${id}/`))
  }
}

在模板中执行v-for="photos in getPhotosById($route.params.id)"