重点输入新添加的项目

ker*_*rby 2 vue.js

所以我有一个项目列表和通过v-for和v-model链接到每个项目的输入列表.

我单击一个按钮并将新项目添加到该列表中.我想关注与新添加的项链接的输入.

无法弄清楚如何实现这一目标.

<div id="app">
  <div v-for="item in sortedItems">
    <input v-model="item">
  </div>
  <button @click="addItem">
    add
  </button>
</div>


new Vue({
  el: '#app',
  data: {
    items: []
  },
  methods: {
    addItem: function() {
      this.items.push(Math.random());
    }
  },
  computed: {
    sortedItems: function() {
      return this.items.sort(function(i1, i2) {
        return i1 - i2;
      })
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

这里是排序列表的小提琴 https://jsfiddle.net/sfL91r95/1/

谢谢

Roy*_*y J 8

更新:灵感来自pkawiak的评论,这是一个基于指令的解决方案.我发现focus在这bind部分打电话不起作用; 我不得不用nextTick它来推迟它.

Vue.directive('focus-on-create', {
  // Note: using Vue 1. In Vue 2, el would be a parameter
  bind: function() {
    Vue.nextTick(() => {
      this.el.focus();
    })
  }
})

new Vue({
  el: '#app',
  data: {
    items: []
  },
  methods: {
    addItem: function() {
      this.items.push(Math.random());
    }
  },
  computed: {
    sortedItems: function() {
      return this.items.sort(function(i1, i2) {
        return i1 - i2;
      })
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
  <div v-for="item in sortedItems">
    <input v-focus-on-create v-model="item">
  </div>
  <button @click="addItem">
    add
  </button>
</div>
Run Code Online (Sandbox Code Playgroud)

原始答案:将您的输入作为一个组件,以便您可以给它一个ready钩子.

const autofocus = Vue.extend({
  template: '<input v-model="item" />',
  props: ['item'],
  ready: function() {
    this.$el.focus();
  }
})

new Vue({
  el: '#app',
  data: {
    items: []
  },
  methods: {
    addItem: function() {
      this.items.push(Math.random());
    }
  },
  components: {
    autofocus
  },
  computed: {
    sortedItems: function() {
      return this.items.sort(function(i1, i2) {
        return i1 - i2;
      })
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
  <div v-for="item in sortedItems">
    <autofocus :item="item"></autofocus>
  </div>
  <button @click="addItem">
    add
  </button>
</div>
Run Code Online (Sandbox Code Playgroud)