时间:2022-07-13 08:28:16 | 栏目:vue | 点击:次
两年前来到新公司,开始使用vue开发,代码复用程度比较低。到后期大量的开发经验,以及看了一些设计模式类的书籍。才开始慢慢总结一些代码复用的经验。分享出来,
PS: Vue版本2.6
<!-- 主文件 -->
<template>
<button @click="clickHandle">button</button>
</template>
<script>
export default {
name: 'PageDemo',
methods: {
func1(){},
func2(){},
func3(){},
clickHandle(){
this.func1();
this.func2()
this.func3()
console.log('button clicked')
}
},
}
</script>
如果当前组件不好拆分,就会出现很多函数,代码会显得不清晰。 我现在的处理方法是通过mixins混入,参照MVC思想,当前文件的的methods只写和模板直接引用的处理方法,其他的函数都通过混入方式引用。
// compose-demo.js
export default {
methods: {
func1(){},
func2(){},
func3(){},
}
}
<template>
<button @click="clickHandle">button</button>
</template>
<script>
// 主文件
import ComposeDemo from './compose-demo'
export default {
name: 'PageDemo',
mixins: [ComposeDemo],
methods: {
clickHandle(){
this.func1();
this.func2()
this.func3()
console.log('button clicked')
}
},
}
</script>
充分利用mixins还有很多优点。
v-model不适用。需要采用$emit方法// 组件
<template>
<input v-model="a" @change="inputChangeHandle"/>
<input v-model="b" @change="inputChangeHandle" />
</template>
<script>
export default {
name: 'ComponentChild',
props: {
propA: {
type: String
},
propB: {
type: String
}
},
data(){
return {
a: this.propA,
b: this.propB,
}
},
methods: {
inputChangeHandle(){
this.$emit('update-data', {a:this.a, b:this.b})
}
}
}
</script>
// 调用方
<template>
<component-child :propA="query.a" :propB="query.b" @update-data="getData"/>
</template>
<script>
import ComponentChild from './component-child.vue'
export default {
name: 'Page1',
components: {ComponentChild},
data(){
return {
query: {
a: '默认数据a',
b: '默认数据b'
}
}
},
methods: {
getData(payload) {
const {a,b}=payload;
this.query.a = a;
this.query.b = b;
}
}
}
</script>
如果你有多处地方需要用到ComponentChild组件,那每个调用地方都需要写一个方法来监听@update-data事件。
此时,可以这样改一下
// 纯函数,引入ComponentChild,并且声明getData方法
// compose-component-child.js
<script>
import ComponentChild from './component-child.vue'
</script>
export default {
components: {ComponentChild},
methods: {
// 通常情况,复用的业务组件都会有同样的数据结构,都带有query.a和query.b。如果不一致,那直接在父组件重写该方法
getData(payload) {
const {a,b}=payload;
this.query.a = a;
this.query.b = b;
}
}
}
// 调用方
<template>
<component-child :propA="query.a" :propB="query.b" @update-data="getData"/>
</template>
<script>
import ComposeComponentChild from './compose-component-child.js'
export default {
name: 'Page1',
mixins: [ComposeComponentChild]
data(){
return {
query: {
a: '默认数据a',
b: '默认数据b'
}
}
},
methods: { }
}
</script>
借鉴了Angular的依赖注入,Page不直接声明、引用Component,而是通过混入Compose直接使用。
Component组件,Compose引入Component并且注册Component(声明额外的方法),Page调用组件混入Compose,就可以可以直接使用Component组件
比如常用的表格需要一下数据
<script>
import {defaultPageSize}from '@/setting'
export default {
data(){
return {
tableList: [],
pageSize: defaultPageSize,
pageNo: 1,
totalRecords: 0,
}
}
}
</script>
以上数据都可以组装为一个compose-table.js文件混入到你要使用的地方,当然也可以通过在compose-table引用注册表格组件。