首页 > 解决方案 > Vue:通过匹配路由查询设置数据

问题描述

我正在尝试设置基于 Vue Router 查询的数组提供的数据字段。例如,当有人使用 登陆我的网站时example.com/?location=texas,我想通过数组设置位置数据。

数组示例:

locations {
    {
        slug: "texas",
        tagline: "Welcome to Texas",
    }, {
        slug: "california",
        tagline: "Welcome to California",
    }
}

我知道这应该使用计算属性来完成,但是我无法获得任何功能。我已经尝试过简单的测试,例如if (this.slug.location === "texas"),我无法获取要填充的位置数据。如果没有路线匹配,我还想提供默认数据

非常感谢任何帮助!

编辑:

我可以以非常手动的方式完成此操作。现在,我通过以下方式在数据中设置查询:

slug: this.$route.query.location

我可以通过执行以下操作来显示特定文本:

h3(v-if="slug === 'texas'") This will show for texas
h3(v-else-if="slug === 'california'") This will show for California
h3(v-else) This is default

这种方法的问题是我需要根据 slug 自定义各种元素。有什么方法可以创建一个数组,并将与数组中的键匹配的数组移动到数据中?

标签: vuejs2computed-properties

解决方案


您应该能够使用以下方式访问查询参数(链接到 Vue 路由器文档):

this.$route.query.location

因此,根据您列出的内容,我会做类似...

export default {
  computed: {
    displayBasedOnLocationQueryParam() {
      switch(this.$route.query.location) {
        case 'texas':
          return 'Welcome to Texas'
        default:
          return 'hello there, generic person'
      }
    }
  }
}

请注意,我没有在那里明确使用您的数组。如果需要,switch 语句可以是该逻辑的唯一来源。


推荐阅读