VueJS Event with Mixins

1

I'm testing Mixins on VueJS and I have a question. How can I call an event directly from a Mixins without having to assign it to my methods ?

MyMixins.js

import Vue from 'vue'

Vue.mixin({
    methods: {
        Alerta(){
            alert('WORK!')
        }
    }
})

app.vue

<template>
   <button v-on:click="AlertaInterno">test</button>
</template>
<script>
   export default{
         methods:{
            AlertaInterno(){
            this.Alerta()
         }
      }
   }
</script>
  

The above code works. I wanted to know how I could invoke the mixin function directly, something like this:

app.vue

<template>
   <button v-on:click="this.Alerta()">test</button>
</template>

Thank you!

    
asked by anonymous 04.10.2017 / 17:07

1 answer

1

You are registering a Global Mixin , you just need to reference the method in the click event with no need to create a new method.

<button v-on:click="Alerta">test</button>

But the documentation leaves an alert.

  

Use global mixins rarely and carefully because they affect each of the Vue instances you create, including third-party components. In most cases, you should only use them to handle custom options, as demonstrated in the example above. It's also a good idea to make them Plugins to avoid duplicate use.

Let's create a basic plugin , it should contain a install and will be called having the Vue constructor as the first argument and other options.

const Alerta = {
  install(Vue, options) {
    Vue.mixin({
      methods: {
        AlertaA() {
          alert("Alerta A!");
        },
        AlertaB() {
          alert("Alerta B!");
        },
        AlertaC() {
          alert("Alerta C!");
        }
      }
    });
  }
};

export default Alerta;

To use

import Vue from "vue";
...
// Plugin
import Alerta from "./alerta.mixins";
Vue.use(Alerta);

The template:

<template>
  <div id="app">
    <button v-on:click="AlertaA">A</button>
    <button v-on:click="AlertaB">B</button>
    <button v-on:click="AlertaC">C</button>
    <button v-on:click="AlertaD">D</button>
  </div>
</template>
  

You can see it working at codesandbox

    
12.03.2018 / 08:38