Vue 使用js来调用一个组件

2,043 阅读1分钟

在引用第三方库的时候,一般都会有通过js来显示一个正确提示或者错误提示的弹窗,如果开发的项目里要有自己独特的风格,可以自己实现一个。

首先,有一个弹窗的组件库(这里就简单写一下,只有报错的)

<template>
 <div v-if="isDialog" class="dialog">
   <div class="content">
     <div class="content-inset">
       <img @click="isDialog=false" class="close" src="@/assets/dialog_close_icon.png" alt="">
       <div class="content-inset-text color-3A1">
         <img src="@/assets/remind_icon.png" alt="">
         <span class="font-size-16">{{ text }}</span>
       </div>
       <div @click="isDialog=false" class="content-inset-bottom">
         <img src="@/assets/confirm_icon.png" alt="">
       </div>
     </div>

   </div>
 </div>
</template>
<script>
export default {
 data () {
   return {
     isDialog: false,
     text: ''
   }
 },
 methods: {
   show (text) {
     this.text = text
     this.isDialog = true
   },
   hide () {
     this.text = ''
     this.isDialog = false
   }
 }
}
</script>
<style lang="scss" scoped>
.dialog{
   .content{
   width: 272px;
   height: 144px;
   background: #fff;
   padding: 2px;
   border-radius: 5px;
   margin-top: 115px;
   .content-inset{
     border: 2px solid #B77F29;
     position: relative;
     width: 100%;
     height: 100%;
     box-sizing: border-box;
     display: flex;
     flex-direction: column;
     justify-content: space-between;
     border-radius: 5px;
     box-shadow: 0 0 4px #ECCDA5 inset;
     background: #FFD98D;
     .close{
       width: 24px;
       height: 24px;
       position: absolute;
       right: 6px;
       top: 6px;
     }
     .content-inset-text{
         display: flex;
         margin: 32px 16px 16px;
         img{
             width: 24px;
             height: 24px;
             margin-right: 8px;
         }
         span{
           flex: 1;
         }

     }
     .content-inset-bottom{
       display: flex;
       justify-content: center;
       img{
         width: 80px;
         height: 50px;
       }
     }
   }
 }
}
</style>

然后将这个组件库放到Vue里面,新建一个index.js

// instance.js

import Vue from 'vue'
import ErrorMsg from './index.vue'

const MsgConstructor = Vue.extend(ErrorMsg)

const instance = new MsgConstructor()

instance.$mount()

document.body.appendChild(instance.$el)

export default instance

在main.js里面引用

import ErrorMsg from '@/components/errorDialog/instance'
Vue.prototype.$errorMsg = instance

下面有两种情况,一种是Vue组件里面引用,一种是js文件引用

Vue组件使用

this.$errorMsg.show('我错了')

js使用

import ErrorMsg from '@/components/errorDialog/instance'
ErrorMsg.show('我错了')