在vue中开发一个简单的消息通知插件

1.新建plugins、msg文件夹以及相关文件

  • src/plugins/index.js
  • src/plugins/msg/msg.vue

2.在msg.vue中实现消息通知的基本功能

  • 点击按钮后弹出一个消息框,几秒之后消失

.msg.vue

<template>
  <div>
    <div class="msg" :class="{'active': msgStatus}">
      <div class="msg-wrapper">
        {{ text }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'vue-msg',
  data () {
    return {
      text: '',
      msgStatus: false
    }
  },
  methods: {
    msgPlugin (msg, time = 2000) {
      this.text = msg
      this.msgStatus = true
      setTimeout(() => {
        this.msgStatus = false
      }, time)
    }
  }
}
</script>

<style scoped>
  .msg {
    position: absolute;;
    left: 50%;
    top: 50%;
    transform: translate(-50%,50%);
    width:0px;
    min-height:0px;
    text-align:center;
    background-color:rgba(0,0,0,0.5);
    border-radius:5px;
    color: #fff;
    transition:all 0.5s;
    z-index:999;
    opacity:0;
  }
  .active {
    width:150px;
    min-height:25px;
    opacity:1;
    z-index:999;
  }
</style>

3.在plugins/index.js 导出插件

//比较简单的写法,后面进行优化
import msg from './msg/msg'

let plugin = {}

plugin.install = function (Vue) {
  Vue.component(msg.name, msg)
}
export default plugin

4.在main.js中引入该插件

import plugin from './plugins'

Vue.use(plugin)

5.在xxx.vue文件中使用vue-msg插件

<template>
  <div class="hello">
    <h1>this is hello word</h1>
    <input placeholder="请输入" v-model="name"/>
    <button @click="submit">提交</button>
    <vue-msg ref="msg"/>
  </div>
</template>

export default {
  name: 'HelloWorld',
  data () {
    return {
      name: ''
    }
  },
  methods: {
    submit () {
      if (!this.name) {
        this.$refs.msg.msgPlugin('姓名不能为空')
      }
    }
  }
}

至此已经完成一个插件的基本开发,但是实际工作中一定会需要在plugins/index.js中导入导出多个插件。第三步的写法不免有些繁琐。
下面提供一种更加优雅的写法

const  requireComponent = require.context('./', true, /\.vue$/)
const install = (Vue) => {
  if (install.installed) return
  install.installed
  requireComponent.keys().map(component => {
    const config = requireComponent(component)
    const componentName = config.default.name
    Vue.component(componentName, config.default || config)
  })
}
export default {
  install,
  // ...components
}

(完)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ## 框架和库的区别?> 框架(framework):一套完整的软件设计架构和**解决方案**。> > 库(lib...
    Rui_bdad阅读 2,979评论 1 4
  • 33、JS中的本地存储 把一些信息存储在当前浏览器指定域下的某一个地方(存储到物理硬盘中)1、不能跨浏览器传输:在...
    萌妹撒阅读 2,112评论 0 2
  • 响应式布局的理解 响应式开发目的是一套代码可以在多种终端运行,适应不同屏幕的大小,其原理是运用媒体查询,在不同屏幕...
    懒猫_6500阅读 806评论 0 0
  • 开发一个项目,采用什么语言都可以,主要能熟练高效的开发都是合理的,这次我们采用vue来开发一个团队项目。在开...
    MsgSS阅读 2,963评论 3 9
  • 首先非常感谢kevinz分享的文章《springboot+gradle+vue+webpack 组合使用》,这文章...
    YU_XI阅读 3,569评论 0 7