VueJS Mixins 方法直接调用

Joh*_*son 3 mixins vue.js vue-component vuejs2

我正在 VueJS 上测试 Mixins,我有一个问题。有没有办法直接从 Mixins 调用事件而不必在 my 中分配它methods

MyMixins.js

import Vue from 'vue'

Vue.mixin({
    methods: {
        Alerta(){
            alert('WORK!')
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

应用程序

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

上面的代码有效。我想知道如何直接调用 mixin 函数,如下所示:

应用程序

<template>
   <button v-on:click="this.Alerta()">test</button>
</template>
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ber*_*ert 5

是的,您可以直接调用它。mixin 中的方法与 Vue 或它们“混入”的组件合并。它们可以像任何其他方法一样被调用。

console.clear()

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

new Vue({
  mixins: [Mixin],
  el: "#app"
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • @Johnson `@click="alerta"` 是 `v-on:click="alerta"` 的简写。它的工作方式没有区别,只是节省了几个字符。同样,您可以使用 `alerta` 或 `alerta()` 调用 `alerta`。如果`alerta` 带参数,你会想要使用`alerta(some, parameters)`。当没有参数时,您只需要单击处理程序中的函数名称。 (2认同)