在下面的示例中,可以使用两个按钮轻松记录 inputBox 的值(我知道这一部分)。但还有第三个按钮,其作用是记录处于焦点/事件状态的 inputBox 的值。在 vue.js 中如何做到这一点
<div id="app">
<br><br><br>
<div v-for="(item,index) in items" :key="index">
<input type="text" v-model="items[index]" >
<button type="submit" @click.prevent="logThisBoxVal(index)">
log this Box
</button>
</div>
<!-- ToDo -->
<br><br>
<button>logActiveBox</button>
</div>
<script>
var application = new Vue({
el: app,
created() {
},
data() {
return {
items: [
"box1", "box2"
]
};
},
methods: {
logThisBoxVal(i) {
console.log(this.items[i])
}
},
computed: {
},
})
</script>
最佳答案
一种方法是向输入添加一个焦点事件,将其定义为事件状态,然后使用该事件在单击 logActiveBox 按钮时选择要 console.log 的事件,如果未选择任何事件,则不输出到控制台。不知道为什么你需要这个。
var application = new Vue({
el: '#app',
data() {
return {
active: null,
items: [
"box1", "box2"
]
};
},
methods: {
logThisBoxVal(i) {
this.active = typeof i !== 'undefined' ? i : this.active
if (this.active !== null) {
console.log(this.items[this.active])
}
}
}
})
/* ignore - used to reduce SO's console output */
.as-console-wrapper {
height: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
<div id="app">
<div v-for="(item,index) in items" :key="index">
<input type="text" v-model="items[index]" @focus="active = index">
<button type="submit" @click.prevent="logThisBoxVal(index)">
log this Box
</button>
</div>
<button @click="logThisBoxVal()">logActiveBox</button>
</div>
关于vue.js - 如何知道 vue.js 中哪个输入是焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67594409/