Home > database >  How do i call a component using event in Vuetify?
How do i call a component using event in Vuetify?

Time:05-19

Currently, i have to add a SnackBar component in my website. The expected output is the snackbar will show up when the user click the submit button. How do i pass my snackbar component to my button located inside my Add.vue file ? This is because I want to reuse my snackbar component because there are multiple submission form.

SnackBar.vue inside component file

<template>
  <div >
    <v-snackbar
      v-model="snackbar"
    >
      {{ text }}

      <template v-slot:action="{ attrs }">
        <v-btn
          color="pink"
          text
          v-bind="attrs"
          @click="snackbar = false"
        >
          Close
        </v-btn>
      </template>
    </v-snackbar>
  </div>
</template>

<script>
  export default {
    data: () => ({
      snackbar: false,
      text: `Hello, I'm a snackbar`,
    }),
  }
</script>

Add.vue

<template>
  <base-form title="Add">
      <template v-slot:actions>
            <v-btn
              color="secondary"
              type="submit"
            >
              <div>Save</div>
            </v-btn>
           
      </template>
 
  </base-form>

</template>

CodePudding user response:

You can import your snack component and pass prop:

Vue.component('snack', {
  template: `
    <div >
      <v-snackbar
        v-model="snackbar"
      >
        {{ text }}

        <template v-slot:action="{ attrs }">
          <v-btn
            color="pink"
            text
            v-bind="attrs"
            @click="$emit('closed', false)"
          >
            Close
          </v-btn>
        </template>
      </v-snackbar>
    </div>
  `,
  props: {
    snackbar: {
      type: Boolean,
      default: false
    }
  },
  data: () => ({
    text: `Hello, I'm a snackbar`,
  }),
})
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    show: false,
  }),
  methods: {
    submit(val) {
      this.show = val
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-btn
          color="secondary"
          type="submit"
          @click="submit(true)"
        >
          <div>Save</div>
        </v-btn>
        <snack :snackbar="show" @closed="submit(false)"></snack>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

  • Related