来自$ refs的Vue.js v-for元素在watch函数中被破坏

问题描述 投票:0回答:1

使用Vue.js 2.5.22和FireFox 65.0。我错过了什么?

https://jsfiddle.net/r083hqgv/2/

v-for属性标识的:ref="x"元素在watch函数中无法正常工作。我也尝试过使用:id="x"getElementById(),并在setTimeout(..., 200)中调用$nextTick()

来自上述小提琴的代码:

<div id="app" style="position:relative">
  <h2>last element top: {{offset+''}}</h2>
  <button @click="add()">Add &amp; 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);
      });
    }
  }
})
javascript vue.js
1个回答
1
投票

正如文档($refs)所引用的那样,this.$refs["..."]在使用v-for时返回一个数组。因此,改变

if (aEl) this.get(aEl);

if (aEl) this.get(aEl[0]);

一切都会奏效(我已经在你的jsfiddle上测试过了)。

© www.soinside.com 2019 - 2024. All rights reserved.