属性或方法“ greet”未在实例上定义,但在渲染期间被引用

问题描述

同一时间,我又遇到另一个错误,即“事件“点击”无效的处理程序”。

<template>
    
    <div id="example-2">
      <!-- `greet` is the name of a method defined below -->
      <button v-on:click="greet">Greet</button>
    </div>
    
    </template>
    
    <script>
    window.onload = function () {
    
    var example2 = new Vue({
      el: '#example-2',data: {
        name: 'Vue.js'
      },// creating method greet
      methods: {
        greet: function (event) {
          // `this` inside methods points to the Vue instance
          alert('Hello ' + this.name + '!')
          // `event` is the native DOM event
          if (event) {
            alert(event.target.tagName)
          }
        }
      }
    })
    
    }
    
    </script>

解决方法

template标签在HTML加载时被隐藏,因此您将收到错误cannot find element或类似的错误。您可以使用javascript加载它。

Vue.js不使用内置的template标记。

但是,如果您在cdn上使用它,请尝试这样

  <div id="example-2">
    <button v-on:click="greet">Greet</button>
  </div>

  <script>
    var example2 = new Vue({
      el: "#example-2",data: {
        name: "Vue.js",},methods: {
        greet: function(event) {
          alert("Hello " + this.name + "!");
          if (event) {
            alert(event.target.tagName);
          }
        },});
  </script>
,

您可以简单地删除template标签

这是工作代码: https://jsfiddle.net/t49zxdov/2/

<div id="example-2">
      <!-- `greet` is the name of a method defined below -->
      <button v-on:click="greet">Greet</button>
    </div>
    
window.onload = function () {
    
        var example2 = new Vue({
      el: '#example-2',data: {
        name: 'Vue.js'
      },// creating method greet
      methods: {
        greet: function (event) {
          // `this` inside methods points to the Vue instance
          alert('Hello ' + this.name + '!')
          // `event` is the native DOM event
          if (event) {
            alert(event.target.tagName)
          }
        }
      }
    })
    
    }
,

您应该分离vue模板和vue实例。为此,

创建文件,例如:example.vue 复制此代码

<template>
    <div id="example-2">
      <!-- `greet` is the name of a method defined below -->
      <button v-on:click="greet">Greet</button>
    </div>
</template>
<script>
  data() {
     return {
         name: 'Vue.js'
     }
  },methods: {
        greet: function (event) {
          // `this` inside methods points to the Vue instance
          alert('Hello ' + this.name + '!')
          // `event` is the native DOM event
          if (event) {
            alert(event.target.tagName)
          }
        }
      }
</script>

并创建此文件,例如:app.js

const app = new Vue({
    el: '#example-2',});

,然后将您的app.js链接到索引布局。

我希望你明白我的意思。谢谢

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...