Skip to content

Instantly share code, notes, and snippets.

@tobiasdalhof
Created September 4, 2020 12:27
Show Gist options
  • Save tobiasdalhof/fefbf9f0336083e1effb7fd7f61039d0 to your computer and use it in GitHub Desktop.
Save tobiasdalhof/fefbf9f0336083e1effb7fd7f61039d0 to your computer and use it in GitHub Desktop.
Global v-snackbar with composition API
<template>
<v-app id="app">
<app-snackbar></app-snackbar>
</v-app>
</template>
<script lang="ts">
import { defineComponent, computed } from '@vue/composition-api'
import AppSnackbar from '@/components/AppSnackbar'
export default defineComponent({
name: 'App',
components: {
AppSnackbar
},
setup() {
return {}
}
})
</script>
<template>
<v-snackbar
v-model="snackbarState.show"
:color="snackbarState.color"
:timeout="snackbarState.timeout"
:dark="snackbarState.dark"
:light="snackbarState.light"
app
>
<span>{{ snackbarState.text }}</span>
<template
v-if="snackbarState.timeout < 0"
v-slot:action="{ attrs }"
>
<v-btn
text
v-bind="attrs"
@click="snackbarState.show = false"
>Schließen</v-btn>
</template>
</v-snackbar>
</template>
<script lang="ts">
import { defineComponent, computed } from '@vue/composition-api'
import { snackbarState } from './'
export default defineComponent({
name: 'AppSnackbar',
setup() {
return { snackbarState }
}
})
</script>
import { snackbar } from '@/components/AppSnackbar'
snackbar({
text: 'Example',
color: 'success'
})
import AppSnackbar from './AppSnackbar.vue'
import { reactive } from '@vue/composition-api'
export default AppSnackbar
interface SnackbarState {
show: boolean
text: string
color: string
timeout: number
dark?: boolean
light?: boolean
}
interface SnackbarOptions {
text: string
color?: string
timeout?: number
dark?: boolean
light?: boolean
}
function snackbarFactory(): SnackbarState {
return {
show: false,
text: '',
color: 'success',
timeout: 3000,
dark: undefined,
light: undefined
}
}
export const snackbarState: SnackbarState = reactive(snackbarFactory())
export function snackbar(options: SnackbarOptions) {
const defaultState = snackbarFactory()
snackbarState.text = options.text
snackbarState.color = options.color || defaultState.color
snackbarState.timeout = options.timeout || defaultState.timeout
snackbarState.dark = options.dark || defaultState.dark
snackbarState.light = options.light || defaultState.light
snackbarState.show = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment