一、方式一
注意:Vue3中一定要有组件名称
示例:封装组件
<script>
export default {
name: 'MyMessage'
}
</script>
<script setup>
...
</scrtpt>
<template>
...
</template>
<style lang="scss" scoped>
...
</style>
1. 新建目录library/index.js
示例:
import MyMessage from '@/components/message/MyMessage'
const components = [
MyMessage
];
export default {
install: app => {
components.forEach(component => {
app.component(component.name, component);
});
}
};
2. 在main.js 引入
示例:
import Ui from '@/library/index.js'
const app = createApp(App)
app.use(Ui).mount('#app')
3. 在组件中使用
<template>
<MyMessage text="手机号或密码错误" type="error"></MyMessage>
</template>
注意:
* 不需要 import 导入
* 可以将该种方式定义为插件
二、方式二
1. 组件封装 MyMessage.vue
示例:
<script setup>
...
</script>
<template>
...
</template>
<style lang="scss" scoped>
...
</style>
2. 函数式方法调用组件
创建新目录message/index.js
import MyMessage from "@/components/message/MyMessage";
import { createVNode, render } from 'vue'
const div = document.createElement('div')
div.setAttribute('class', 'xtx-massage-container')
document.body.appendChild(div)
let timer = null
export default ({ type, text }) => {
const vnode = createVNode(MyMessage, { type, text })
render(vnode, div)
clearInterval(timer)
timer = setTimeout(() => {
render(null, div)
}, 3000)
}
3. 使用
* 定义hooks方法
import MyMessage from "@/components/message/index";
export function useMessage() {
const error = (text) =>{
MyMessage({
text: text ,
type: "error"
})
}
return {
error
}
}
* 组件使用
<script setup>
import {useMessage} from "@/hooks/useMessage";
const {error} = useMessage()
const handleBtn = () =>{
error('失败')
}
<script>