写给小白的 Vue 插件篇

79 阅读1分钟

目的

“插件通常用来为 Vue 添加全局功能。”
“组件是可复用的 Vue 实例,且带有一个名字。”
—— Vue.js 官网

官网插件例子做的比较粗糙,不能顺畅的理解插件,故自己试试

实操

1、先写插件内容(类似组件)

<!-- src/components/Warning/index.vue -->
<template>
  <transition name="fade">
    <p v-show="isShow" class="msg">{{ msg }}</p>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      msg: 'warning',
      isShow: false,
      duration: 1,
    }
  },
  mounted() {
    this.isShow = true
    setTimeout(() => {
      this.isShow = false
    }, this.duration * 1000)
  },
}
</script>

<style>
.msg {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

2、手动挂载 warning 的 dom

// src/components/Warning/index.js 
import Vue from 'vue'
import Warning from './index.vue'

const WarningConstructor = Vue.extend(Warning) // 生成构造器

const warning = function(options={}) {
    const warningChild = new WarningConstructor({ // 实例
        data:options
    }).$mount() // 挂载

    const realDom = warningChild.$el // 真实 dom
    document.body.appendChild(realDom)

    return warningChild
}

export default warning

3、暴露 install 方法 传入 Vue.use()

// src/components/index.js
import waring from './Toast/index';

// Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象
const install = function (Vue) {
  if (install.installed) return;
  install.installed = true;

  // 将包装好的 warning 挂到Vue的原型上,作为 Vue 实例上的方法
  Vue.prototype.$waring = waring;
}

export default {
  install,
};

4、使用

// main.js
import waring from '../src/components/index.js';
Vue.use(waring);
// App.vue
<template>
    <button @click="handleClick">点击弹出文字</button>
</template>

methods: {
    handleClick() {
      this.$waring()
    },
  },

效果展示

Kapture 2023-03-08 at 15.00.54.gif

  • good 下节见!