代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test auto reload</title>
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="searchDiv">
<input id="searchIpt" type="text"/>
<input id="searchBtn" type="button" value="搜索"/>
<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>
<script type="text/javascript">
var data = [{'title': 'hello1'}, {'title': 'hello2'}];
loadDataList();
document.getElementById('searchBtn').onclick = function () {
if (document.getElementById('searchIpt').value == '1') {console.log(1);
data = [{'title': 'hello3'}, {'title': 'hello4'}];
loadDataList();
} else if (document.getElementById('searchIpt').value == '2') {console.log(2);
data = [{'title': 'hello5'}, {'title': 'hello6'}];
loadDataList();
}
};
function loadDataList() {
var app = new Vue({
el: '#searchResult',
data: {
searchResultList: data
}
});
}
</script>
</body>
</html>
我希望输入框里输入1或者2后,点击搜索按钮页面的数据列表自动刷新,现在的问题是不管我搜1还是2,列表一直展示的是 hello1 hello2 。请大神帮忙看看,谢谢。
通过修改 app.searchResultList 这种方法使数据发生变化的方法我是知道的哦,请大神帮忙看看如何仅修改 loadDataList 这个方法里的代码实现这个需求呢?
你非要调用
loadDataList
不行是因为第一次
new Vue({ el: "#searchResult" })
,获取到的是模板:这个模板内有
v-if
和v-for
有变量searchResultList
但是你第二次点击调用
new Vue({ el: '#searchResult' })
时,因为已经渲染内容了,所以获取到的是<ul><li>hello1</li><li>hello2</li></ul>
这就是为啥不管怎么点击都是
hello1
,因为根本就没有模板了vue
的核心是数据驱动视图,所以修改data
数据就行了