编写 vuetify 全局 snackbar

2022-04-25 19:09:19 浏览数 (3)

components/snackbar.vue

代码语言:javascript复制
<template>
  <v-snackbar v-model="open" :bottom="bottom" :color="color" :timeout="2000">{{ msg }}</v-snackbar>
</template>
 
<script lang='ts'>
import { Component, Vue } from "vue-property-decorator";

@Component
export default class Snackbar extends Vue {
  color: any = "";
  open: boolean = false;
  msg: any = "";
  bottom: boolean = true;

  info(msg: any) {
    this.color = "rgb(33,150,243)";
    this.msg = msg;
    this.open = true;
  }

  success(msg: any) {
    this.color = "rgb(76,175,80)";
    this.msg = msg;
    this.open = true;
  }

  warning(msg: any) {
    this.color = "rgb(255, 170, 0)";
    this.msg = msg;
    this.open = true;
  }

  error(msg: any) {
    this.color = "rgb(255,82,82)";
    this.msg = msg;
    this.open = true;
  }
}
</script>

utils/snackbar.ts

代码语言:javascript复制
import Vuetify from 'vuetify';
import Vue from 'vue';
import Snackbar from '@/components/snackbar.vue';

Vue.use(Vuetify)
const v = new Vue({
  render(createElement) {
    return createElement(Snackbar);
  },
  vuetify: new Vuetify(),
})

v.$mount()

document.body.appendChild(v.$el);
const snackbar: any = v.$children[0];
function info(msg: any) {
  snackbar.info(msg);
}

function error(msg: any) {
  snackbar.error(msg);
}

function warning(msg: any) {
  snackbar.warning(msg);
}

function success(msg: any) {
  snackbar.success(msg);
}

export default {
  info,
  success,
  warning,
  error
}

main.ts

代码语言:javascript复制
import snackbar from '@/utils/snackbar';

Vue.prototype.$snackbar = snackbar;

usage

代码语言:javascript复制
this.$snackbar.success('this is a success msg');

this.$snackbar.error('this is a error msg');

this.$snackbar.warning('this is a warning msg');

this.$snackbar.info('this is a info msg');

0 人点赞