基于Vue封装API形式的组件

需求:封装一个弹窗组件。

遇到的问题:

  1. 传统的封装方式使用时需要在每个使用的页面,引入组件,注册组件,绑定参数

这种方式使用起来相当繁琐,因为每次使用都需要重复步骤,因此有了下面这样的想法,将方法挂载到vue原型,需要使用的时候。调API就行了,但是遇到了一些问题,上代码

问题描述

封装一个弹窗组件。

问题出现的环境背景及自己尝试过哪些方法

传统的封装方式使用时需要在每个使用的页面,引入组件,注册组件,绑定参数

相关代码

import vue from 'vue'

// 导入组件

import Toast from './toast.vue'

// 生成一个扩展实例构造器

const ToastConstructor = vue.extend(Toast)

//定义一个变量用于保存vue实例

let _Toast = {}

//定义弹窗的函数 接收两个参数 title message

const showToast = (option)=>{

//实例化构造器

_Toast = new ToastConstructor({

data(){

return{

showToast:true,

title:option.title,

message:option.message

}

}

})

// 生成模板

const element = _Toast.$mount().$el

console.log(_Toast.showToast)

// 如何防止重复添加节点?

document.body.appendChild(element)

}

}

//定义隐藏弹窗的函数

const hideToast = () => {

_Toast.showToast = false

}

showToast.install = Vue =>{

Vue.prototype.$toast = showToast

}

hideToast.install = Vue=>{

Vue.prototype.$hideToast = hideToast

}

//导出

export {showToast,hideToast}

你期待的结果是什么?实际看到的错误信息又是什么?

理想状态是能够像element message 弹窗那样通过API调用

实际的问题:

项目结构及代码截图

坐等大佬教学一波封装方式,或者给出一些资料(百度的已经找了)

回答

给你写个示例作为参考思路

// toast.js

export const Toast = {

name: 'toast',

props: {

title: {

type: String,

required: true

}

},

render (h) {

return h('div', {

style: {

backgroundColor: 'rgba(0,0,0,0.3)',

color: '#fff',

width: 'fit-content',

padding: '.5rem',

borderRadius: '6px',

marginBottom: '1rem'

}

}, this.title)

}

}

export default {

install (vue, config) {

const ToastComponent = vue.extend(Toast)

vue.prototype.$toast = function (title) {

const instance = new ToastComponent({ propsData: { title } })

const anchor = document.createElement('div')

window.document.body.appendChild(anchor)

instance.$mount(anchor)

setTimeout(() => {

window.document.body.removeChild(instance.$el)

instance.$destroy()

}, 1500)

}

}

}

使用

// main.js

import Toast from './toast'

Vue.use(Toast)

// 代码中

this.$toast('hay man!')

之前参考过这一篇文章:
https://zhuanlan.zhihu.com/p/...
写过 loading 组件

防止重复添加的实现大概就是用一个 ref 和一个全局boolean called 来做的

正好之前自己封装过toast弹窗,简直手摸手文章。

Vue 封装Toast消息提示
https://segmentfault.com/a/11...

都配有GitHub地址

自己封装的,https://github.com/ZFCFBGC/vue2.96_demol
仅供参考

以上是 基于Vue封装API形式的组件 的全部内容, 来源链接: utcz.com/a/37459.html

回到顶部