第一步
首先需要搭建一个Vue项目,可以按照从0到1创建一个Vue项目,先进行安装
第二步
在components目录下新建一个文件夹notice,在notice文件夹下创建一个index.js一个notice.vue
第三步
现在就可以在notice.vue写出组件的结构
<template>
<div>
标题:{{title}}
提示:{{message}}
</div>
</template>
<script>
export default {
data () {
return {
title: '',
message: ''
}
}
</script>
第四步
在index.js中将组件抛出
,参考Vue.extend( options )使用方法
import Vue from 'vue'
import notice from './notice'
const NoticeContructor = Vue.extend(notice)
export default function noticeFn (options) {
/**
* options:{
* title:'xxx'
* message:'yyy'
* }
*/
// 1.实例化
const instance = new NoticeContructor({
data: options
})
// 2.手动挂载
instance.$mount() // dom元素渲染完成
// 3.手动挂载到Body
document.body.appendChild(instance.$el)
return instance
}
第四步
在main.js中进行挂载
import notice from './components/notice/index'
// 可以将notice挂载到Vue构造函数的原型上,由于继承关系,所有的组件实例就都可以通过this..$notice()进行调用
Vue.prototype.$notice = notice
第五步
在页面中进行调用,查看效果
<el-button @click="open">默认按钮</el-button>
methods: {
open () {
this.$notice({
title: '提示',
message: '这是一条不会自动关闭的消息'
})
}
}