在Vue项目中实现全局调用,js中调用组件,this,$方案调用

需求:

首先能传参,想要在全局中调用组件,而且要在某些js文件内调用,还能在任意组件内像this.$router这种调用。组件内有很多功能,要能监听到组件内的不止两个的事件。

开始:

vue组件

<template>
  <div class="container" >
    <div @click="sendTitle">题目</div>
    {{ content }}
    <span @click="sentFoot">尾部</span>
  </div>
</template>

<script>
export default {
  name: 'message-tip',
  props: {
    duration: {
      type: Number,
      default: 3000
    },
    content: {
      type: String,
      default: 'q'
    }
  },
  components: {},
  methods: {
    showTitle() {
      console.log(2222);
    },
    sendTitle() {
      this.$emit('gogo',123456)
    },
    sentFoot() {
      this.$emit('ww',6666666)
    }
  }
};
</script>

<style lang="scss" scoped></style>

index.js

// /src/components/MessageBox/index.js

import messageTipVue from './index.vue';
// 定义插件对象
const MessageTip = {};
// vue的install方法,用于定义vue插件
MessageTip.install = function(Vue, options) {
  console.log(options)
  const MessageTipInstance = Vue.extend(messageTipVue);
  let currentMsg;
  const initInstance = () => {
    // 实例化vue实例
    currentMsg = new MessageTipInstance();
    let msgBoxEl = currentMsg.$mount().$el;
    document.body.appendChild(msgBoxEl);
  };
  // 在Vue的原型上添加实例方法,以全局调用
  Vue.prototype.$msgTip = {
    showTip(options) {
      if (!currentMsg) {
        initInstance();
      }
      if (typeof options === 'string') {
        currentMsg.content = options;
      } else if (typeof options === 'object') {
        Object.assign(currentMsg, options);
      }
      return currentMsg; // 为了链式调用
    }
  };
};
export default MessageTip;

然后在main.js里这样子

import MessageTip from '@/components/message-tip';
Vue.use(MessageTip);

然后调用

某个组件内调用

created() {
    this.$msgTip
      .showTip({
        content: '12112312312'
      })
      .$on('gogo', function(data) {
        // 监听我刚才在组件中的事件
        alert(data);
      })
      .$on('ww', function(dd) {
       // 监听我刚才在组件中的事件
        alert(dd);
      });
  },

某工具js函数内使用

import Vue from 'vue';
Vue.prototype.$msgTip
    .showTip({
      content: '12112312312'
    })
    .$on('gogo', function(data) {
      alert(data);
    })
    .$on('ww', function(dd) {
      alert(dd);
    });

只是简单的例子,有了这个流程那接下来的路就通畅了。

原创文章 112 获赞 173 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_41229588/article/details/105434270
今日推荐