Vue3 setup的业务逻辑分离功能拆分
在Vue3开发中,我们可能遇到一个页面或者组件业务逻辑很复杂,代码量达到千行,不利于阅读和维护,因此需要将业务逻辑进行分离
首页主界面 index.vue
// index.vue
<script>
import {reactive, toRefs} from 'vue'
import useOperate from './useOperate.js'
import useConfig from './useConfig.js'
export default {
name: '',
setup(props, {emits, slot, attr}){
const { title, getList } = useOperate();
const { onEditHandler, onDeleteHandler } = useConfig();
const state = reactive({
myTitle: title
})
return {
...toRefs(state),
onEditHandler,
onDeleteHandler
}
}
}
</script>
功能拆分1:useOperate.js
import { reactive, toRefs } from 'vue'
export default function useOperate(){
const state = reactive({
fromData: {
title: ""
}
})
// 函数
const getList = () => {
...
}
return {
...toRefs(state),
getList
}
}
功能拆分2: useConfig.js
import {reactive, toRefs} from 'vue'
export default function useConfig(){
const onEditHandler = () => {...}
const onDeleteHandler = () => {...}
return {
onEditHandler,
onDeleteHandler
}
}