# 增加/编辑模板复用
我们经常在 进行数据的添加和编辑操作, 都需要共用一套模板, 我们可以用一个变量进行控制
父组件
<template>
<article-detail :is-edit="true" /> // is-edit 用于控制 是否处于编辑或是增加
</template>
<script>
import ArticleDetail from './components/Detail'
export default {
name: 'EditBook',
components: { ArticleDetail }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
子组件
<template>
<div class="createPost-container">
<el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
<sticky :z-index="10" :class-name="'sub-navbar ' + postForm.status">
<el-button v-if="!isEdit" @click.prevent.stop="showGuide">显示帮助</el-button>
<el-button v-loading="loading" style="margin-left: 10px;" type="success" class="submit-btn" @click="submitForm">
{{ isEdit ? '编辑电子书' : '新增电子书' }}
</el-button>
</sticky>
<div class="createPost-main-container">
.........
</div>
</el-form>
</div>
</template>
<script>
import { createBook, getBook, updateBook } from '@/api/book'
export default {
name: 'Detail',
components: { MDinput, Upload, Sticky, Warning },
props: {
isEdit: {
type: Boolean, // 变量类型
default: false
}
},
data() {
return {
postForm: Object.assign({}, defaultForm),
}
},
computed: {},
created() {
// 如果为编辑, 就需要拿到路由参数, 获取数据详情 ⭐⭐⭐
if (this.isEdit) {
const fileName = this.$route.params && this.$route.params.fileName
this.getBookData(fileName)
}
},
mounted() {
},
methods: {
submitForm() {
this.$refs.postForm.validate(valid => {
if (valid) {
const book = Object.assign({}, this.postForm)
// 如果this.isEdit 为假, 表示编辑, 执行编辑操作 ⭐⭐⭐
if (!this.isEdit) {
createBook(book).then(response => {
..........
})
})
} else {
// 否则为 增加 执行添加操作⭐⭐⭐
updateBook(book).then(response => {
.......
})
})
}
}
})
},
}
}
</script>
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66