函数式组件
相信每个朋友都用过vue的UI框架,如ElementUI,iview等
在使用时有些会用到通过一个函数来调用组件
比如Element中的this.$message()来调用一个弹出框消息的组件
这里就来跟大家说说在vue2.x是怎么实现的,vue3抽空写
文件结构:
message
·····main.vue
·····index.js
·····index.sacc
1.message.vue
<template>
<div class="g">
<div :class="{
'msg-wb': 1,
'msg-up': position=== 'up',
'msg-down': position=== 'down',
'msg-left': position=== 'left',
'msg-right': position=== 'right',
'msg-success': type === 'success',
'msg-warning': type === 'warning',
'msg-danger': type === 'danger',
'msg-primary': type === 'primary',
'msg-error': type === 'error'
}" >{{ message }}</div>
</div>
</template>
<script>
export default {
data() {
return {
message: '消息为空',
position: 'up',
type: 'primary'
}
}
}
</script>
<style scoped>
//这里根据不同的class 自己写样式,博主也懒得写
</style>
2.index.js
import Main from "./main.vue";
import Vue from "vue";
const MessageConstructor = Vue.extend(Main);
// 这里面要处理逻辑得话自行加上就可
const Message = obj => {
let { during } = obj;
during = during || 2000
//这里data就是组件里面得data,如果没传就会使用main.vue里得data
const msg = new MessageConstructor({data:obj})
msg.$mount()
document.body.appendChild(msg.$el);
setTimeout(() => {
document.body.removeChild(msg.$el)
}, during)
};
export default Message;
3.在main.js
import msg from "./components/message"
Vue.prototype.$msg = msg
**4.**在about.vue中
<button @click="good">123</button>
methods: {
good () {
this.$msg({
during: 2500
})
}
}