我试图专注于下一个动态插入的输入,我可以关注foobar_x而不是v-for循环中的那些。任何帮助将不胜感激。
Codepen:https://codepen.io/Moloth/pen/qPRGvz
new Vue({
el: '#app',
data: {
test: "xxxxxx",
phones: [
{number: "0000000"},
{number: "1111111"},
],
},
methods: {
focusPhones: function() {
this.$refs.foobar_1.focus()
},
focusTest: function() {
this.$refs.foobar_x.focus()
}
}
})

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script>
<div id="app">
<v-text-field label="foobar_x" ref="foobar_x" v-model="test"></v-text-field>
<div v-for="(value, i) in phones" :key="i">
<v-text-field :label="'foobar_'+i" :ref="'foobar_'+i" v-model="phones[i].number"></v-text-field>
</div>
<v-btn @click.native="focusPhones()">Focus foobar_1</v-btn>
<v-btn @click.native="focusTest()">Focus foobar_x</v-btn>
</div>
&#13;
答案 0 :(得分:4)
当您向ref
循环中的元素添加v-for
值时,将在this.$refs['name-of-your-value']
中生成一个数组,并且该元素或组件的引用将被推送到该数组
因此,由于您是通过:ref="'foobar_'+i"
动态添加引用,因此对这些组件的引用将位于this.$refs.foobar_0[0]
和this.$refs.foobar_1[0]
。但是,如果您只是指定相同的ref
值(例如foobar_y
),则Vue会为您执行索引编制工作,您的组件可以在this.$refs.foobar_y[0]
和this.$refs.foobar_y[1]
访问。
这是一个有效的例子:
new Vue({
el: '#app',
data: {
test: "xxxxxx",
phones: [
{number: "0000000"},
{number: "1111111"},
],
},
methods: {
focusPhones: function() {
this.$refs.foobar_y[1].focus()
},
focusTest: function() {
this.$refs.foobar_x.focus()
}
}
})
&#13;
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script>
<div id="app">
<v-text-field label="foobar_x" ref="foobar_x" v-model="test"></v-text-field>
<div v-for="(value, i) in phones" :key="i">
<v-text-field :label="'foobar_'+i" ref="foobar_y" v-model="phones[i].number"></v-text-field>
</div>
<v-btn @click.native="focusPhones()">Focus foobar_y[1]</v-btn>
<v-btn @click.native="focusTest()">Focus foobar_x</v-btn>
</div>
&#13;