Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

基于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调用

实际的问题:
image

项目结构及代码截图
image

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

// 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!')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...