VueJS Mixins Methods Direct Call

佐手、 提交于 2021-02-10 04:01:46

问题


I'm testing Mixins on VueJS and I have a question. Is there a way to call an event directly from a Mixins without having to assign it in 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 code above works. I was wondering how I could invoke the mixin function directly, something like this:

app.vue

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

Thanks!


回答1:


Yes, you can call it directly. Methods from the mixin are merged with the Vue or component they are "mixed in" with. They can be called the same way as any other method.

console.clear()

const Mixin = {
  methods:{
    Alerta(){
      alert("WORK!")
    }
  }
}

new Vue({
  mixins: [Mixin],
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
 <button @click="Alerta">Alert!</button>
</div>


来源:https://stackoverflow.com/questions/46592331/vuejs-mixins-methods-direct-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!