2017-10-05 422 views
0

我在VueJS上测试Mixins,我有一个问题。有没有办法直接从Mixins调用事件,而无需将其分配在我的methods中?VueJS Mixins方法直接调用

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> 

上述工程的代码。我想知道我怎么能直接调用混入功能,这样的事情:

app.vue

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

谢谢!

回答

1

是的,你可以直接调用它。来自mixin的方法是合并与Vue或它们“混合在一起”的组件。它们可以像其他方法一样被调用。

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>

+0

感谢的人! “@ click”或“v-on:click”之间有什么不同之处? – Johnson

+0

有时我会使用'()'来看看人们在做什么,'@ click =“alerta”'而不是'@ click =“alerta()”'。这些代码有什么区别? – Johnson

+1

@Johnson'@ click =“alerta”'是v-on的简写:click =“alerta”'。它的工作方式没有什么区别,只是保存了几个字符。同样,您可以使用'alerta'或'alerta()'调用'alerta'。如果'alerta'带有参数,那么你会想使用'alerta(一些参数)'。当没有参数时,你只需要在点击处理程序中使用函数名称。 – Bert