
vue.js数据驱动视图:解决搜索结果刷新问题
在Vue.js应用中,动态更新页面数据是常见需求。本文将分析一个Vue组件数据自动刷新失效的案例,并提供解决方案。
问题描述:
一个简单的搜索功能,用户输入“1”或“2”后点击搜索按钮,预期列表数据会更新。但实际运行中,列表始终显示初始数据“hello1 hello2”。
错误代码:
立即学习“前端免费学习笔记(深入)”;
<div id="searchDiv">
<div id="searchResult" v-cloak="">
<ul v-if="searchResultList.length"><li v-for="res in searchResultList">{{res.title}}</li></ul>
<ul v-else><li>无记录</li></ul>
</div>
</div>
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}
});
}问题分析:
PbootCMS是一款高效、简洁、强悍的开源PHP企业网站开发建设管理系统。 PbootCMS 1.1.8 更新日志:2018-08-07 1.修复提交表单多选字段接收数据问题; 2.修复登录过程中二次登陆在页面不刷新时验证失败问题; 3.新增搜索结果fuzzy参数来控制是否模糊匹配; 4.新增父分类,顶级分类名称及链接独立标签,具体见手册; 5.新增内容多图拖动排序功能。
243
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。
以上就是Vue.js数据更新失败:为何搜索结果无法自动刷新?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号