问题描述
我在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' })
}
},}
URL为/search/?q=somesearch
问题是,如果我不带查询参数就打/ search /,它将立即出现错误Unable to encode undefined of type undefined
,这很显然是因为它试图用未定义的值查询API,但是我不能似乎可以找到有效的检查方法,以便在未设置查询的情况下不查询API,而只显示搜索框。
我尝试过
if query.q !== undefined
在try部分中,但这不起作用。
解决方法
要检查未定义的值,可以使用:
if (typeof query.q !== 'undefined')
typeof
以字符串形式返回数据类型,这使得检查未定义的值成为可能。