【问题标题】:Vue: Setting Data by matching route queryVue:通过匹配路由查询设置数据
【发布时间】:2021-04-27 02:45:23
【问题描述】:

我正在尝试设置基于 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 自定义各种元素。有什么方法可以创建一个数组,并将与数组中的键匹配的数组移动到数据中??

【问题讨论】:

    标签: vuejs2 computed-properties


    【解决方案1】:

    您应该能够使用以下 (link to Vue Router documentation) 访问查询参数:

    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 语句可以是该逻辑的唯一来源。

    【讨论】:

    • 这很好,但是我需要数据是持久的,并且理想情况下会通过匹配数组或类似的东西来填充数据集。我已经编辑了原始帖子以获取更多详细信息。
    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多