Vue:TypeError:_vm.myFunction 不是函数

问题描述

我正在尝试在 .vue 文件添加一个简单的按钮,以使用以下代码将某些内容记录到控制台:

<template>
  <div>
    <button v-on:click="sayHello()">Click me</button> 
  </div>
</template>
<script>
export default {
  data() {
  },methods: {
    sayHello: function () {
      console.log('Hello!')
    }
  },};

我在控制台中收到以下错误

TypeError: _vm.sayHello is not a function

Property or method "sayHello" is not defined on the instance but referenced during render. Make sure that this property is reactive,either in the data option,or for class-based components,by initializing the property.

我看过一些教程说你应该把它添加到数据中,但它只是说 sayHello() 是未定义的,或者当我在 sayHello() 中定义 data 时,它说 {{ 1}} 已定义但从未使用过。

我什至尝试过以下操作:

sayHello()

但它给了我这个错误

<button v-on:click="console.log('Hello!')">Click me</button>

有人可以帮我解决这个问题吗?这可能是我没有尝试过的非常明显的事情。

解决方法

您没有在 <script> 之后关闭标记 export default { ... }

为了更好的可读性,我编辑了语法。

<template>
  <div>
    <button @click="sayHello">Click me</button> 
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },methods: {
    sayHello() {
      console.log('Hello!');
    },},};
</script>

对于 click 事件不一定需要调用带有 () 的方法。但尽管两种变体都是正确的。

,

错误在这里

wrong
v-on:click="sayHello()" 


correctly
v-on:click="sayHello" 
<template>
  <div>
    <button @click="sayHello">Click me</button> 
  </div>
</template>
<script>
export default {
  data() {
  },methods: {
    sayHello () {
      console.log('Hello!')
    }
  },}