admin管理员组

文章数量:1794759

Vue 使用 函数调用组件 的方法

Vue 使用 函数调用组件 的方法

之前写过一篇 react 方法组件构造 Loading 的使用,

现在这篇就是 Vue 版本的 方法调用组件了

组件还是 vue 组件,这个和之前是一样的

Toast/Toast.vue <template> <div class="toast" v-if="show"> <div class="mask" v-if="showMask"></div> <div class="message">{{ message }}</div> </div> </template> <script> export default { data() { return { showMask: false, message: '', t: null, show: false } }, methods: { showToast({ message = '', showMask = false, length = 3000 }) { this.message = message this.showMask = showMask this.show = true this.t && clearTimeout(this.t) this.t = setTimeout(() => { this.show = false }, length) }, hideToast() { this.show = false }, destory() { this.$destroy() } } } </script> <style lang="less" scoped> .toast { .mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.1); z-index: 100; } .message { color: white; background-color: rgba(0, 0, 0, 0.6); border-radius: 5px; padding: 10px; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -60%); z-index: 100; } } </style> Toast/index.js import Vue from 'vue' import Toast from './Toast.vue' let toastVue function createToast() { // 这里使用了 VUE 来构建一个 vnode // 值得注意的是, $mount() 函数没有填写任何的 dom 节点 // 这样就变成了一个 未挂载 的 vnode const vnode = new Vue({ render: h => h(Toast) }).$mount() // 手动 将 生成的对应 dom 插进 body 里面 document.body.appendChild(vnode.$el) // 返回当前实例 的 vue 对象 // 没错,就是 $children[0] return vnode.$children[0] } export function showToast(args, callback) { // 为了让当前的实例 只有一个,防止占用太多内存 if (!toastVue) { toastVue = createToast() } toastVue.showToast(args) callback && callback() return toastVue } export function hideToast() { if (!toastVue) return toastVue.hideToast() return toastVue } export function destoryToast() { if (!toastVue) return toastVue.destory() } export default showToast 关于 调用: import ShowToast from '@/components/Toast' created() { // 这样就能对 当前的 Toast 组件进行调用了 ShowToast({ message: 'hhhhh', showMask: true }) }

页面效果:

 

本文标签: 函数组件方法Vue