- 创建一个Vue组件
- 创建该组件的Vue实例
- 挂载在Vue.prototype上
- 使用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创建组件实例
- 使用Vue.extend
- 使用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})
}).$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)
}