Vuejs内联编辑简单示例

示例1

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<div class="app-container">
<div v-for="field in fields" :key="field.id" class="editable-field">
<template v-if="editedFieldId === field.id">
<input type="text" v-model="field.value" :ref="`field${field.id}`" />
<button class="btn" @click.prevent="toggleEdit">
<template>Save</template>
</button>
</template>
<template v-else>
<span class="editable-text">
{{ field.value }}
</span>
<button class="btn" @click.prevent="toggleEdit(field.id)">Edit</button>
</template>
</div>
</div>
</template>

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
export default {
name: "InlineEdit",
props: {},
data() {
return {
editedFieldId: null,
fields: [
{
id: 1,
value: "Editable field 1",
},
{
id: 2,
value: "Editable field 2",
},
],
};
},
created() { },
mounted() { },
methods: {
toggleEdit(id) {
if (id) {
this.editedFieldId = id;
this.$nextTick(() => {
if (this.$refs["field" + id]) {
this.$refs["field" + id][0].focus();
}
});
} else {
this.editedFieldId = null;
}
},
},
};

示例2

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<div class="container">
<input
type="text"
v-if="edit"
:value="valueLocal"
@blur="onBlur($event)"
@keyup.enter="onKeyEnter($event)"

v-focus
/>
<span v-else @click="edit = true">
{{ valueLocal }}
</span>
</div>
</template>

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<script>
export default {
name: "ClickToEdit",
props: ["value"],

data() {
return {
edit: false,
valueLocal: this.value,
};
},

watch: {
value: function () {
this.valueLocal = this.value;
},
},

directives: {
focus: {
inserted(el) {
el.focus();
},
},
},

methods:{
onBlur(ev){
this.valueLocal = ev.target.value;
this.edit = false;
this.$emit('input', this.valueLocal);
},
onKeyEnter(ev){
this.valueLocal = ev.target.value;
this.edit = false;
this.$emit('input', this.valueLocal);
}
}
};
</script>

参考链接

  1. Vue Inline edit,by yobyzal.
  2. Building a form with inline editing,by stackoverflow.
  3. Simple inline editable fields with Vue.js,by devrecipes.