【问题标题】:Checking empty query parameter in nuxt检查nuxt中的空查询参数
【发布时间】:2021-02-14 04:54:59
【问题描述】:

我的 Prismic/Nuxt 项目中有一个搜索页面,它对 Prismic API 进行全文查询。

这段代码可以做到这一点

export default {
  name: 'Search',
  async asyncData({ $prismic, params, query, error }) {
    try {
      // Query to get post content

      const products = await $prismic.api.query($prismic.predicates.fulltext('my.product.title', query.q), { orderings: '[my.product.title desc]' })
      // Returns data to be used in template
    
      return {
        products: products.results,
      }
    } catch (e) {    
      // Returns error page
      error({ statusCode: 404, message: 'Page not found' })
    }
  },
}

网址是/search/?q=somesearch

问题是,如果我在没有查询参数的情况下点击 /search/,它会立即遇到错误 Unable to encode undefined of type undefined,这显然是因为它尝试使用未定义的值查询 API,但我似乎不能了解如何进行有效检查,以便在未设置查询时不查询 API,而只显示搜索框。

我试过了

if query.q !== undefined 

在尝试部分,但这不起作用。

【问题讨论】:

    标签: javascript html vue.js nuxt.js prismic.io


    【解决方案1】:

    要检查未定义的值,您可以使用:

    if (typeof query.q !== 'undefined')

    typeof 将数据类型作为字符串返回,这使得检查未定义值成为可能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2019-05-30
      • 2016-04-02
      • 2014-09-03
      • 2020-07-05
      • 1970-01-01
      • 2023-01-09
      相关资源
      最近更新 更多