使用Vue创建一个toast

492 阅读1分钟
  1. 创建一个Vue组件
  2. 创建该组件的Vue实例
  3. 挂载在Vue.prototype上
  4. 使用this.$toast({content: '哈哈哈'})

1. 创建一个Vue组件

<template>
    <div class="box">
        {{content}}
    </div>
</template>

<script>
export default {
    props: {
        content: {
            type: String,
            default: ""
        },
        duration: {
            type: Number,
            default: 2000
        }
    },
    mounted() {
        setTimeout(() => {
            document.body.removeChild(this.$el)
            this.$destroy()
        }, this.duration)
    }
}
</script>

2. Vue创建组件实例

  1. 使用Vue.extend
  2. 使用new Vue

使用Vue.extend

  • 使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。
  • 创建实例,并挂载(挂载之后$el可以访问到真实dom)。
import Vue from 'vue'

export default function create(component, props) {
    const Ctor = Vue.extend(component)
    const vm = new Ctor({ propsData: props }).$mount()
    return vm
}

使用new Vue

  • new Vue({render() {}}),在render中把Component作为根组件
  • 拿到孩子实例
import Vue from 'vue'

export default function create(component, props) {
    const rvm = new Vue({
        render: h => h(component, {props}) // h(标签名称或组件配置对象,传递属性、事件等,孩子元素)
    }).$mount()
    const vm = rvm.$children[0]
    return vm
}

挂载在Vue.prototype上

import create from '@/utils/create'
import Toast from '@/components/Toast'

Vue.prototype.$toast = (props) => {
  let vm = create(Toast, props)
  document.body.appendChild(vm.$el)
}