vue3 如何分离组件的公共逻辑?

 

问题描述:

<template lang="pug">
.container vue3
</template>

<script setup>
import { provide } from "vue"

const props = defineProps({
    msg: {
        type: String,
        default: "",
        // required: true
    },
})

let data = $ref({
    a:1
})
provide("data", data)

const emit = defineEmits(["change"])

const demo = () => {
    console.log("demo")
}
defineExpose({
    demo,
})
</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 100%;
}
</style>

以上是一个基本的vue组件,我不介意各种语法糖, 好用就用,所以我全用。

问题是:

我有几个逻辑完全一样的组件,但页面结构与样式不同,请问怎样提取逻辑代码?
看网上的教程,一言难尽……大部分都是提取方法到js里再导入


 

第 1 个答案:

我有两个建议

1. 只写一个组件,用 props 区分样式结构

<Comp scene="A" />

<Comp scene="B" />
<template>
    <SceneA v-if="scene===A" />
    <SceneB v-if="scene===B" />
<template>
<script setup>
// ...组件逻辑
<script>

2. 使用组合式函数抽离逻辑

// 你的所有逻辑
export default function useComp() {
    return {}; // xxxx
}
<template>
  <div>{{xxxx}}</div>
<template>
<script setup>
const { xxxx } = useComp();
<script>
<template>
  <span>{{xxxx}}</span>
<template>
<script setup>
const { xxxx } = useComp();
<script>

参考:https://cn.vuejs.org/guide/re...


 

第 2 个答案:

确实是要这样。vue3一般封装成 use hook,把通用的方法抽离到hooks里面,然后在组件中单独引入,可以参考element-plususeOption
如果你这些组件有公用组件,你也可以把这个公用组件拆出来当一个子组件,这样也能减少一部分代码。


我看到有这样的示例:// 1.使用常量指定固定的属性值。 ...