Javascript v-for的VueJS forceUpdate不工作
本周我开始学习VueJS,当时我正试图构建一个便笺应用程序,但遇到了一些问题:Javascript v-for的VueJS forceUpdate不工作,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,本周我开始学习VueJS,当时我正试图构建一个便笺应用程序,但遇到了一些问题: 笔记: +加 及 Vue.component('notelist'{ 道具:[“注意”], 模板:'{{note.title}}-{{note.text}}' }); x=[ {id:1,标题:“代码”,文字:“我今晚应该编码”}, ] if(localStorage.getItem(“notes”)==null){ setItem(“notes”,JSON.stringify(x)); } var app=新
笔记:
+加
及
Vue.component('notelist'{
道具:[“注意”],
模板:'{{note.title}}-{{note.text}} '
});
x=[
{id:1,标题:“代码”,文字:“我今晚应该编码”},
]
if(localStorage.getItem(“notes”)==null){
setItem(“notes”,JSON.stringify(x));
}
var app=新的Vue({
el:“#应用程序”,
数据:函数(){
返回{
注释:JSON.parse(localStorage.getItem(“注释”),
};
},
方法:{
addnewnote(){
var nte=document.getElementById(“ntitle”).value;
var ntt=document.getElementById(“ntext”).value;
var nid=JSON.parse(localStorage.getItem(“notes”)).length+1;
var sd={id:nid,title:nte,text:ntt};
var NI=JSON.stringify(JSON.parse(localStorage.getItem(“notes”)).concat(sd));
setItem(“notes”,NI);
这是。$forceUpdate()
},
}
});
基本上,我在localstorage上存储注释,当单击+Add
时,会添加一个新注释,但问题是添加新项目时列表不会重新呈现!
这是我的repl您还需要更新方法'addnewnote()中的
notes
组件数据属性:
这是为了让Vue组件知道数据属性发生了更改,并可以相应地进行更新。通过此更改,您将不需要forceUpdate()。Vue不会监视localStorage的更改并自动更新notes组件数据属性,您需要手动执行此操作
这是一个正在实施的计划
还请考虑避免使用DOM方法来获取输入属性,而实际上使用VUE V模型将输入的值绑定到组件数据属性。
<input v-model="ntitle" id="ntitle">
<input v-model="ntext" id="ntext">
// ...
data: function () {
return {
ntext: '',
ntitle: '',
notes: JSON.parse(localStorage.getItem("notes")),
};
}
// ...
const sd = { id: nid, title: this.ntitle, text: this.ntext };
// ...
数据:函数(){
返回{
ntext:“,
第三条:“,
注释:JSON.parse(localStorage.getItem(“注释”),
};
}
// ...
const sd={id:nid,title:this.ntitle,text:this.ntext};
希望这有帮助 谢谢,我只需要做一点修改,
this.notes=JSON.parse(NI)
asNI
以前是JSON stringyfied。当然,我更新了答案以反映这一点。您可以考虑在变量中保存和使用解析的JSON,而不是多次解析和严格化。如果有帮助,请标出答案。谢谢
addnewnote() {
const nte = document.getElementById("ntitle").value;
const ntt = document.getElementById("ntext").value;
const nid = JSON.parse(localStorage.getItem("notes")).length + 1;
const sd = { id: nid , title: nte , text: ntt };
const NI = JSON.parse(localStorage.getItem("notes")).concat(sd);
this.notes = NI;
localStorage.setItem("notes" , JSON.stringify(NI));
this.$forceUpdate()
}
<input v-model="ntitle" id="ntitle">
<input v-model="ntext" id="ntext">
// ...
data: function () {
return {
ntext: '',
ntitle: '',
notes: JSON.parse(localStorage.getItem("notes")),
};
}
// ...
const sd = { id: nid, title: this.ntitle, text: this.ntext };