Vue.js $refs 中的 v-for 元素在 watch 函数中损坏
Vue.js v-for element from $refs broken in watch function
使用 Vue.js 2.5.22 和 FireFox 65.0。我错过了什么?
https://jsfiddle.net/r083hqgv/2/
由 :ref="x"
属性标识的 v-for
元素在 watch
函数中无法按预期工作。我也尝试过使用 :id="x"
& getElementById()
,并在 $nextTick()
.
中调用 setTimeout(..., 200)
上面的代码fiddle:
<div id="app" style="position:relative">
<h2>last element top: {{offset+''}}</h2>
<button @click="add()">Add & get top</button>
<ol>
<li v-for="a in list" :key="'r.'+a">
<a @click.stop.prevent="get($event.target)" href="#"
:ref="'r.'+a">get top {{'r.'+a}}</a>
</li>
</ol>
</div>
new Vue({
el: "#app",
data: {
offset: 0,
last: 'unset',
list: [],
},
methods: {
add: function() {
this.last = 'r.'+ this.list.push(this.list.length+1);
this.list = this.list.slice();
},
get: function(iEl) {
this.offset = iEl.offsetTop;
iEl.style = 'font-style:italic';
}
},
watch: {
list: function() {
this.$nextTick(function() {
var aEl = this.$refs[this.last];
if (aEl) this.get(aEl);
});
}
}
})
如文档 ($refs) 所引用,this.$refs["..."]
returns 使用 v-for
时的数组。因此,更改
if (aEl) this.get(aEl);
到
if (aEl) this.get(aEl[0]);
一切正常(我已经在你的 jsfiddle 上测试过了)。
使用 Vue.js 2.5.22 和 FireFox 65.0。我错过了什么?
https://jsfiddle.net/r083hqgv/2/
由 :ref="x"
属性标识的 v-for
元素在 watch
函数中无法按预期工作。我也尝试过使用 :id="x"
& getElementById()
,并在 $nextTick()
.
setTimeout(..., 200)
上面的代码fiddle:
<div id="app" style="position:relative">
<h2>last element top: {{offset+''}}</h2>
<button @click="add()">Add & get top</button>
<ol>
<li v-for="a in list" :key="'r.'+a">
<a @click.stop.prevent="get($event.target)" href="#"
:ref="'r.'+a">get top {{'r.'+a}}</a>
</li>
</ol>
</div>
new Vue({
el: "#app",
data: {
offset: 0,
last: 'unset',
list: [],
},
methods: {
add: function() {
this.last = 'r.'+ this.list.push(this.list.length+1);
this.list = this.list.slice();
},
get: function(iEl) {
this.offset = iEl.offsetTop;
iEl.style = 'font-style:italic';
}
},
watch: {
list: function() {
this.$nextTick(function() {
var aEl = this.$refs[this.last];
if (aEl) this.get(aEl);
});
}
}
})
如文档 ($refs) 所引用,this.$refs["..."]
returns 使用 v-for
时的数组。因此,更改
if (aEl) this.get(aEl);
到
if (aEl) this.get(aEl[0]);
一切正常(我已经在你的 jsfiddle 上测试过了)。