Vue2.x 中注册插件

由于插件更具灵活性,所以我们可以自定义组件注册成全局组件。按照 Vue 的约定,我们需要将我们的项目结构做一下调整。

src/plugin目录下建一个和组件名称一致的文件夹,然后将我们上面定义的 splash.vue 文件放到这个目录下面,然后在这个目录下面再建一个index.js的文件,通过在这个文件里面写注册代码,将我们的自定义组件注册成插件。示例代码如下所示:

import Splash from './Splash'

export default {
    install: function (Vue, options) {
        // 1.获取构造函数
        const contructor = Vue.extend(Splash)
        // 2. 实例化组件对象
        const instance = new contructor()
        // 3. 创建页面元素
        const oDiv = document.createElement('div')
        document.body.appendChild(oDiv)
        // 4. 将组件挂载到页面元素上
        instance.$mount(oDiv)
        if (options !== null && options.title !== undefined) {
            instance.title = options.title
        }
        // 添加全局方法
        Vue.ToggleSplash = function () {
            instance.isShow = !instance.isShow;
        }
        // 添加实例方法
        Vue.prototype.$ToggleSplash = function () {
            instance.isShow = !instance.isShow;
        }
    }
}

在 main.js 中,引入插件

// 1. 导入自定义组件
import Splash from './plugin/splash/index'

// 2. 将自定义组件注册成组件
Vue.use(Splash, { title: 'hello world' })

接下来,我们就可以在 任何组件中通过调用 Vue 对象的全局方法或实例方法来控制我们的自定义组件,比如,我们可以在hello-world这样使用:

<template>
  <div class="hello">
    <h1>{
   
   { msg }}</h1>
    <button @click="toggle1">使用全局方法控制显示或隐藏插件</button>
    <button @click="toggle2">使用实例方法控制显示或隐藏插件</button>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  methods: {
    toggle1: function () {
      // 通过全局方法来访问自定义组件
      Vue.ToggleSplash();
    },
    toggle2: function () {
      // 通过实例方法来访问自定义组件
      this.$ToggleSplash();
    },
  },
};
</script>

<style scoped>
.hello {
  border: 1px dashed #00f;
}
</style>

转载于:Vue2.x 中注册自定义组件的3种方式

猜你喜欢

转载自blog.csdn.net/godread_cn/article/details/129490537
今日推荐