vue中定义插件

插件通常用来为Vue添加全局功能,一般有下面几种情况:

1.添加全局方法或属性

2.添加全局资源:指令/过滤器/过渡等

3.通过全局混入来添加一些组件选项

4.添加Vue实例方法,通过添加到Vue.prototype上实现

5.一个库,提供自己的API,同时提供上面提到的一个或多个功能

在脚手架中定义插件的过程,以Toast插件为例

1.在components文件夹中创建toast文件夹,再toast文件夹下创建文件Toast.vue,代码如下:

<template>
  <div v-show="isShow" class="toast">
    <div>{{message}}</div>
  </div>
</template>

<script>
  export default {
    name: 'Toast',
    data() {
      return {
        message: '',
        isShow: false
      }
    },
    methods: {
      show(message, duration = 2000) {
        this.isShow = true
        this.message = message

        setTimeout(() => {
          this.isShow = false
          this.message = ''
        }, duration)
      }
    },
  }
</script>

<style scoped>
.toast{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  padding: 8px 10px;
  border-radius: 10px;
  color: #fff;
  background-color: rgba(0,0,0,.7);
  z-index: 999;
}
</style>

 

2.在Toast.vue文件同级创建index.js文件,Vue.js的插件应该暴露一个install方法,其第一个参数是Vue构造器,第二个参数是一个可选的选项对象,代码如下:

import Toast from './Toast'
const obj = {}


obj.install = function(Vue) {
  // 1.创建组件构造器
  const toastConstructor = Vue.extend(Toast)

  // 2.根据组件构造器,可以创建出来一个组件对象
  const toast = new toastConstructor()

  // 3.将组件对象手动挂载到一个元素上
  toast.$mount(document.createElement('div'))

  // 4.toast.$el对应的就是div  Toast模板添加到body上
  document.body.appendChild(toast.$el)

  // 5.添加到vue原型上
  Vue.prototype.$toast = toast
}

export default obj

3.在main.js中导入插件,并安装插件

import toast from 'components/toast'


Vue.use(toast)  //会调用toast中的install方法执行

4.在其他组件实例中使用

this.$toast.show('提示信息')

 

posted @ 2022-09-14 10:37  jxweber  阅读(65)  评论(0)    收藏  举报