Reputation: 633
I'm trying to use a clic edit vuejs comonent with switch from text-> input.
The process is I clic on the text it switch to the input html tag. Good but then I need to re-clicl to enter text.
How can I proceed to enter text as soon as I click the first time ?
<template>
<el-input
v-if="edit"
v-focus=""
type="text"
:value="local"
placeholder="place"
@blur.native="
local = $event.target.value;
edit = false;
$emit('input', local);
"
@keyup.enter.native="
local = $event.target.value;
edit = false;
$emit('input', local);"
/>
<p v-else="" @click="edit = true" > {{ local }}</p>
</template>
<script>
export default {
props: ["value"],
data() {
return {
edit: false,
local: this.value,
};
},
watch: {
value: function () {
this.local = this.value;
},
},
directives: {
focus: {
inserted(el) {
el.focus();
},
},
},
};
</script>
Upvotes: 0
Views: 1134
Reputation: 7090
You need to have access to the DOM element to trigger the focus on it. To do this, add a the ref
attribute to your input: ref="inputField"
And in you your script: this.$refs.inputField.$el.focus();
<template>
<el-input
v-if="edit"
ref="inputField"
type="text"
:value="local"
placeholder="place"
@blur.native="
local = $event.target.value;
edit = false;
$emit('input', local);
"
@keyup.enter.native="
local = $event.target.value;
edit = false;
$emit('input', local);"
/>
<p v-else="" @click="startEdit" > {{ local }}</p>
</template>
<script>
export default {
props: ["value"],
data() {
return {
edit: false,
local: this.value,
};
},
watch: {
value: function () {
this.local = this.value;
},
},
methods: {
startEdit() {
this.edit = true;
this.$refs.inputField.focus();
},
},
};
</script>
https://v3.vuejs.org/guide/component-template-refs.html
Upvotes: 1