[Vuejs]-How can I reuse Vue and Vuetify code?

2πŸ‘

I think creating a mixin works as well:

Say that you create alertMixin.js as below:

const alertMixin = {
  data () {
    return {
      myAlert: false,
      text: '',
      color: 'success',
    }
  },
  methods: {
    openAlt (text, color) {
      this.text = text;
      this.color = color;
      this.myAlert = true;
    }
  }
};

export default alertMixin;

And use it where ever you want like this:

<script>
import alertMixin from '@/path/to/mixin/alertMixin';

export default {
  name: 'where-ever-you-want',
  mixins: [alertMixin],
};
</script>
πŸ‘€Syed

1πŸ‘

Hi welcome to vuetiful world of vue.

You can easily do that making the alert as an component and importing it where ever you want.

For any file where you want to use your alert code, you could just import your alert component and use it just like any other HTML component.

import alert from './path/to/component

<template>
    <appAlert></appAlert>
</template>

<script>
 components:{
     appAlert: alert
}
</script>

There more you can do with components, Read about Vue components

I hope it helps.

0πŸ‘

Here’s my new code.

App.vue

<template>
  <v-app>
    <v-content>
      <router-view/>
    </v-content>
    <alt></alt>
  </v-app>
</template>

<script>
export default {
  name: 'App'
}
</script>

main.js

// ...
import alt from './components/alt'

Vue.prototype.$EventBus = new Vue()
Vue.config.productionTip = false

Vue.component('alt', alt)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

alt.vue

<script>
export default {
  data () {
    return {
      my_alert: false,
      text: '',
      color: 'success'
    }
  },
  created () {
    this.$EventBus.$on('show_alt', (str, color) => {
      var text = str
      var clr = color

      if (!text) text = 'μ„€μ •λ˜μ§€ μ•Šμ€ 문ꡬ'
      if (!clr) clr = 'error'

      this.text = text
      this.color = clr
      this.my_alert = true
    })
  }
}
</script>
<template>
  <div>
      <v-snackbar v-model="my_alert"
            :timeout="2000"
            :color="color"
            top right>
      {{ text }}
      <v-btn icon ripple @click="my_alert = false">
        <v-icon>close</v-icon>
      </v-btn>
    </v-snackbar>
  </div>
</template>

At last, altTest.vue

<template>
  <v-btn @click="openAlt('This is alert', 'error')">Click Me!</v-btn>
</template>

<script>
export default {
  data () {
    return {

    }
  },
  methods: {
    openAlt (str, color) {
      return this.$EventBus.$emit('show_alt', str, color)
    }
  }
}
</script>

I imported alt.vue to main.js as global, and it’s added App.vue.

So, I can open alert in altTest.vue without import(but, it need a method openAlt()).

But, I think this is not simple..

Leave a comment