VUE组件封装Tips

在开发项目时我们往往都需要去封装一些组件出来。封装有这些好处:代码重用、不必关心具体的实现、面向对象三大特征之一、具有安全性。但如果封装的不好,组件的封装会使得维护起来特别麻烦,适得其反,那让我们看看封装组件时应该注意哪些事项吧

1.遵循高内聚原则 

高内聚:又称单一责任原则,是指一个模块只负责一项任务。在我们组件中体现在一个组件只有一项功能,若是功能太复杂,那我们还需将组件进行拆解抽离。

像下面这个内容展示组件,里面包含了三个模块功能:搜索框、展示列表、操作栏。那我们可以将它提取成三个组件来引用。这样当你需要复用其中一项功能模块时就能直接使用。

<template>
  <Search searchContent="searchContent"></Search>
  <Operation operationlist="operationlist"></Operation>
  <TableList datalist="datalist"></TableList>  
</template>
<script setup>
import Search from './components/search.vue'
import Operation from './components/operation.vue'
import TableList from './components/tableList.vue'
defineProps({
  searchContent: String,
  operationlist: Array,
  datalist:Array
})
</srcipt>

 2.遵循低耦合原则

耦合:指的是模块之间的依赖性强弱。模块之间的依赖性越弱则称为耦合度低,反之耦合度就越高。

由于vue是单向数据流,在我们封装组件时,尽量使用父传子props,子传父emit,避免子组件直接操作父组件数据

 ①父组件

//父组件
<template>
    <div>子组件的值:{
   
   { children_msg }}</div>
    <children :msg="msg" @childmsg="childmsg"></children>
</template>

<script setup>
import {ref} from 'vue';
import children from './children.vue';
let msg = "我是父组件"
const children_msg = ref("") 
let childmsg = (val) => {
    children_msg.value = val
}
</script>

②子组件

//子组件
<template>
    <div>父组件的值:{
   
   { msg }}</div>
    <button @click="fathermsg">传值给父组件</button>
</template>

<script setup>
import {defineProps,defineEmits} from 'vue';
defineProps({
    msg: {
        type: String,
        default: ""
    }
})
const emit = defineEmits(['childmsg'])
const fathermsg = () => {
    const father_msg = "我是子组件"
    emit('childmsg',father_msg);
}
</script>

3.避免嵌套太多层

在开发过程中,我们往往会遇到一些组件多层嵌套的情况,当你不断抽离,层次太多,维护起来往往比较困难,这时候我们可以将一些不必要封装的功能适当放在一起,避免出现父组件>子组件>孙组件>……的情况

 ①过度封装的Search组件

//组件Content
<template>
    <Search></Search>
    ……
</template>
//孙组件Search
<template>
    <SearchInput></SearchInput>
    <SearchButton></SearchButton>
</template>
//曾孙组件SearchInput
<template>
    <div><input type="text"/></div>
</template>

②优化Search组件

上述的Search组件没必要将其输入框和按钮作为单一的组件使用,我们完全可以将其作为一个组件看待

//孙组件Search
<template>
    <div>
        <input type="text"/>
        <button>搜索</button>
    </div>
</template>

4.留一个插槽位置

在开发过程中,我们往往会碰到一些封装的ui组件,如弹窗往往需要传头部或者尾部来修改默认样式;表格框传一些需要添加的操作按钮。为了适应所有的场景,我们留一个插槽位置是需要的。

①父组件

//父组件
<template>
  <child>
      <!-- 子组件中slot标签被替换为了我们插入的button按钮 -->
      <button>插槽按钮</button>
  </child>
</template>

<script setup>
import child from "./child.vue"
</script>

②子组件

//子组件
<template>
  <div>
    <p>我是子组件</p>
    <!-- 插槽 -->
    <slot></slot>
  </div>
</template>

猜你喜欢

转载自blog.csdn.net/weixin_42214717/article/details/127486085
今日推荐