arrays - Vue 的数据项数组仅在硬编码时在过滤器中工作,而不是在包含为(n echo'ed PHP)数组时
问题描述
我的行为很奇怪,我被卡住了;/
我有/使用了这个数组:
[
{
"Question": "business metrics",
"Answers": "how well assistant ..."
},
{
"Question": "technical metrics",
"Answers": "how well is ..."
},
{
"Question": "business metrics types",
"Answers": "CSAT, coverage ..."
},
{
"Question": "key metrics",
"Answers": "precision, accuracy ..."
}
]
这是由生成的:
$json = json_decode(file_get_contents('assets/feeds/questions.json'), 1);
$flattened_array = call_user_func_array('array_merge', $json);
$data = json_encode($flattened_array, JSON_PRETTY_PRINT);
我在 Vue 中包含该数据,因此我可以动态过滤 Q 和 A。这仅适用于使用以下代码的 Q:
new Vue({
el: '#app',
data: {
searchValue: '',
courselines: <?php echo $data ?>
},
computed: {
filteredCourselines() {
let tempCourselines = this.courselines;
// Process search input
if (!tempCourselines) {
return [];
}
if (this.searchValue !== '' && this.searchValue) {
return tempCourselines.filter(function (q) {
return q.Question.toLowerCase().indexOf(searchValue) >= 0;
});
} else {
return [];
}
}
}
});
但是,我注意到一旦我将问题更改为答案,或者将其添加为或运算符,事情就会停止工作。
return tempCourselines.filter(function (q) {
return q.Answers.toLowerCase().indexOf(searchValue) >= 0 || q.Question.toLowerCase().indexOf(searchValue) >= 0;
});
我花了几个小时才发现,当我用硬编码的数组数据替换 PHP 回显时,一切都很好。
这是匹配的 HTML 块:
<div id="app" class="m-5">
<div id="wrapper">
<input type="text" v-model="searchValue" placeholder="Search Term" class="my-4" id="search-input"></input>
<div id="courseline-container">
<div class="card p-2 m-2" v-for="(courseline, index) in filteredCourselines" :key="index">
<div class="content">
<span>
<p><strong>{{ courseline.Question }}</strong><br/>{{ courseline.Answers }}</p>
</span>
</div>
</div>
</div>
</div>
</div>
我不明白为什么,有人有线索吗?
编辑:
我发现某些答案中的空值会导致错误。我需要知道如何在不破坏空值的情况下运行过滤器:
[
{
"Question": "business metrics",
"Answers": "how well assistant ..."
},
{
"Question": "technical metrics",
"Answers": "how well is ..."
},
{
"Question": "business metrics types",
"Answers": "CSAT, coverage ..."
},
{
"Question": "Scenarios",
"Answers": null
},
{
"Question": "key metrics",
"Answers": "precision, accuracy ..."
}
]
解决方案
根据您的评论,您的实际数据集可能具有null
某些Answers
属性,从而导致运行时出错。
您可以使用可选链接( ?.
) 来避免null
错误:
return tempCourselines.filter(function (q) {
return q.Answers?.toLowerCase().indexOf(searchValue) >= 0 || q.Question.toLowerCase().indexOf(searchValue) >= 0;
});
第一个条件在is或(表示在可能的答案中未找到搜索undefined
值)时返回(假值),然后短路到下一个条件,检查.q.Answers
undefined
null
q.Question
推荐阅读
- file - 如何很好地阅读“交替”行?
- android - Wi-fi 未连接到 Android Studio 模拟器
- amazon-web-services - 资源 'data.template_file.user_data' 没有属性 'rendered'
- java - 在 SpringBoot 中提供 Developer 和 Production URL Mail 链接
- jquery - 使用带有 a-frame 的 jquery 接收未定义的错误
- python - Tkinter 按钮链接到带参数的函数给出 TypeError
- java - 无法在另一台 PC 上运行可执行 JAR 文件
- php - 在我将 php 版本从 7.1 切换到 7.2 或 7.2 到 7.1 之前,WebServer 无法工作
- amazon-web-services - 如何在一个 API Gateway REST API 中为多个自定义授权者编写策略?
- python - Qthread 上的 QTimer