Reputation: 9583
In the example below the value of the inputBox can be logged easily using two buttons( I know this part ). but there is a third button whose job is to log the value of inputBox which is in focus / active. How can this be done in 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>
Upvotes: 2
Views: 1487
Reputation: 46660
One way would be to add a focus event to the input which defines it as active then use that to select which one to console.log when the logActiveBox button is clicked, if none have been selected then don't output to console. No idea why you would need this.
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>
Upvotes: 2