You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中PHP注入数组过滤Answers字段失效,硬编码正常,如何兼容null值

问题原因

报错的核心原因是当Answers字段为null时,直接对null调用.toLowerCase()方法会抛出类型错误,直接中断整个过滤流程。除此之外原有代码还存在隐性问题:filter回调函数内直接使用searchValue未加this指向,部分场景下也会触发变量未定义报错。

解决方法

直接修改过滤逻辑,对字段做空值兼容处理,遇到null/undefined时自动转为空字符串再做匹配即可,修改后的filteredCourselines计算属性代码如下:

computed: {
    filteredCourselines() {
        let tempCourselines = this.courselines;
        // 提前统一转搜索词为小写,避免循环内重复处理
        const searchTerm = this.searchValue ? this.searchValue.toLowerCase() : '';

        if (!tempCourselines || searchTerm === '') {
            return [];
        }

        return tempCourselines.filter(function (q) {
            // 空值兼容:非字符串值自动转为空字符串再处理
            const questionText = (q.Question || '').toLowerCase();
            const answerText = (q.Answers || '').toLowerCase();
            return questionText.indexOf(searchTerm) >= 0 || answerText.indexOf(searchTerm) >= 0;
        });
    }
}

可选优化方案(非必须)

如果不想每次过滤都处理空值,也可以在数据生成/初始化阶段统一把null的Answers字段替换为空字符串:

  1. PHP端处理:
$json            = json_decode(file_get_contents('assets/feeds/questions.json'), 1);
$flattened_array = call_user_func_array('array_merge', $json);
// 统一处理空值
foreach ($flattened_array as &$item) {
    $item['Answers'] = $item['Answers'] ?? '';
}
$data            = json_encode($flattened_array, JSON_PRETTY_PRINT);
  1. Vue端初始化时处理:
new Vue({
    el: '#app',
    data: {
        searchValue: '',
        // 初始化时统一替换空值
        courselines: <?php echo $data ?>.map(item => ({
            ...item,
            Answers: item.Answers || ''
        }))      
    },
    // 剩余逻辑不变
})

内容的提问来源于stack exchange,提问作者Kim K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:15:03