Vue3 使用hoks封装弹窗组件
时间: 2023-11-02 07:04:53 浏览: 200
在Vue3中使用Hooks封装弹窗组件,可以通过自定义Hooks来实现。具体实现步骤如下:
1. 创建一个名为useModal的Hooks:
```javascript
import { ref } from 'vue'
export default function useModal() {
const visible = ref(false)
function showModal() {
visible.value = true
}
function hideModal() {
visible.value = false
}
return {
visible,
showModal,
hideModal
}
}
```
2. 在组件中使用useModal Hooks:
```javascript
<template>
<div>
<button @click="showModal">打开弹窗</button>
<div v-if="visible">
<!-- 弹窗内容 -->
<button @click="hideModal">关闭弹窗</button>
</div>
</div>
</template>
<script>
import useModal from './useModal'
export default {
setup() {
const { visible, showModal, hideModal } = useModal()
return {
visible,
showModal,
hideModal
}
}
}
</script>
```
通过这种方式,我们可以轻松地封装一个弹窗组件,并且可以在多个组件中复用。同时,由于Vue3中使用Composition API,代码更加简洁易懂,方便维护。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)