【问题标题】:Change Data in Vue Component depending on Route根据路由更改 Vue 组件中的数据
【发布时间】:2019-11-19 14:12:27
【问题描述】:

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

该网站可以在这里看到: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 }
        ]
    });

【问题讨论】:

  • 您可以使用$route.params.id查看您所在的网站,并据此显示照片
  • 我如何在const subitem = { data() {中创建一个if语句

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


【解决方案1】:

您可以使用 Vue-router 的功能 Dynamic Route Matching 并在组件中使用 this.$route.params.id 访问 :id

或者你可以pass route parameters as props。 只需将您的路由定义更改为{ path: '/Portfolio/:id', component: subitem, props: true }, 并在您的subitem 组件中定义id 属性

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

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

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

【讨论】:

  • 太好了。我想为每个页面创建一个数组,例如飞机和动物等。我想使用v-for="subitem in $route.params.id" 但是这会循环遍历每个字符并且不会给出整个单词以与数据数组匹配
  • 因为传递的id 只是值,目录的名称。您可以使用它来过滤所有照片数组。编辑了我的答案以添加示例.....
  • 谢谢你的工作。只需将计算更改为方法即可
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 2017-08-12
  • 2019-07-17
  • 2016-10-26
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多