想使用 Vue 写一个页面,集成各种自己需要的功能,以供 Wallpaper Engine 使用。结果在一开始就碰到了问题——页面数据不更新。
原来的代码:
let englishWords = new Vue({
el: "#english-words",
data: {
words: words[2].data,
curWord: {}
},
methods: {
show(){
let {len,curIndex} = {len:this.words.length,curIndex:0};
this.interval = setInterval(() => {
if(curIndex === len){
curIndex = 0;
}
this.curWord.word = this.words[curIndex].word;
this.curWord.phonetic = `[${this.words[curIndex].phonetic}]`;
this.curWord.word_explain = this.words[curIndex].word_explain.replace(/\\n/g,'<br />');
curIndex++;
},1000)
},
clearShow(){
clearInterval(this.interval);
}
},
created(){
this.show();
}
})
更改后的代码:
let englishWords = new Vue({
el: "#english-words",
data: {
words: words[2].data,
curWord: {
word:'',
phonetic:'',
word_explain:''
}
},
methods: {
show(){
let {len,curIndex} = {len:this.words.length,curIndex:0};
this.interval = setInterval(() => {
if(curIndex === len){
curIndex = 0;
}
this.curWord.word = this.words[curIndex].word;
this.curWord.phonetic = `[${this.words[curIndex].phonetic}]`;
this.curWord.word_explain = this.words[curIndex].word_explain.replace(/\\n/g,'<br />');
curIndex++;
},1000)
},
clearShow(){
clearInterval(this.interval);
}
},
created(){
this.show();
}
})
更改后可以正常更新数据。变动只有 data 里面 curWord 部分,目前还不知道为什么。我的猜测是 curWord 里面要表明有哪些属性,这样 vue 才可以监测其变化,如果一开始没有,即使以后添加,vue 也无法监测变化。
好吧,看了一下 vue 的教程,其中有一句:“值得注意的是只有当实例被创建时 data 中存在的属性才是响应式的。” 看来我对这句话的理解还不够。即使是深层次的属性也要在一开始写明。