在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);
    });

只是簡單的例子,有了這個流程那接下來的路就通暢了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM