Vuejs Event with Mixins

Asked

Viewed 94 times

1

I’m testing Mixins on Vuejs and I have a question. It’s like I call an event directly from a Mixins without having to assign in mine methods ?

Mymixins.js

import Vue from 'vue'

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

app.

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

The above code works. I wondered how I could invoke mixin function directly, something like this:

app.

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

Thank you!

1 answer

1


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

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

But the documentation leaves a warning.

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

Come create a plugin basic, it should contain a method install and will be called having the builder Vue as 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 in codesandbox

  • Perfect!! Thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.