首页 > 文章列表 > Vue.js数据更新失败:为何搜索结果无法自动刷新?

Vue.js数据更新失败:为何搜索结果无法自动刷新?

280 2025-03-25

Vue.js数据更新失败:为何搜索结果无法自动刷新?

Vue.js数据驱动视图:解决搜索结果刷新问题

在Vue.js应用中,动态更新页面数据是常见需求。本文将分析一个Vue组件数据自动刷新失效的案例,并提供解决方案。

问题描述:

一个简单的搜索功能,用户输入“1”或“2”后点击搜索按钮,预期列表数据会更新。但实际运行中,列表始终显示初始数据“hello1 hello2”。

错误代码:

  • {{res.title}}
  • 无记录
var data = [{'title': 'hello1'}, {'title': 'hello2'}]; loadDataList(); document.getElementById('searchBtn').onclick = function () { if (document.getElementById('searchIpt').value == '1') { data = [{'title': 'hello3'}, {'title': 'hello4'}]; loadDataList(); } else if (document.getElementById('searchIpt').value == '2') { data = [{'title': 'hello5'}, {'title': 'hello6'}]; loadDataList(); } }; function loadDataList() { var app = new Vue({ el: '#searchResult', data: {searchResultList: data} }); }

问题分析:

loadDataList函数每次都被调用,创建了新的Vue实例。这导致Vue无法追踪数据变化,视图不会自动更新。

解决方案:

只创建一个Vue实例,直接修改其数据。Vue会自动检测数据变化并更新视图。

正确代码:

var data = [{'title': 'hello1'}, {'title': 'hello2'}];
var app = new Vue({
    el: '#searchResult',
    data: {searchResultList: data}
});
document.getElementById('searchBtn').onclick = function () {
    if (document.getElementById('searchIpt').value == '1') {
        app.searchResultList = [{'title': 'hello3'}, {'title': 'hello4'}];
    } else if (document.getElementById('searchIpt').value == '2') {
        app.searchResultList = [{'title': 'hello5'}, {'title': 'hello6'}];
    }
};

通过直接修改app.searchResultList,Vue自动更新视图,实现了数据自动刷新。这展示了Vue数据驱动视图的优势,无需手动操作DOM。

来源:1740769685