Property or method not defined in .vue file

2019-07-27 18:06发布

Everything in my app was working perfectly fine until I began to add my javascript. Now I continuously get errors in the console.

I get this error:

Property or method "show" 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.

As well as this error:

TypeError: _vm.show is not a function
  at click App.vue?d98c:25
  at HTMLButtonElement.invoker vue.esm.js?efeb:1906

Desired Outcome: Click on "loginBtn" alert prompts "click".


My code:

// app.vue script 
export default {
  name: 'app'
}

var show = new Vue({
  el: '#loginBtn',
  data: {
    n: 0
  },
  methods: {
    show: function(event) {
      targetId = event.currentTarget.id;
      alert('click')
    }
  }
})

<!-- the button -->
<template>
  <div>
    <button v-on:click="show($event)" id="loginBtn">Login</button>
  </div>
</template>

1条回答
ゆ 、 Hurt°
2楼-- · 2019-07-27 18:38

You are using a Single-File Component (a .vue file), which is a file format for a Vue component definition used by vue-loader.

The script section of a .vue file (what's inside the <script> tag) should export an object specifying the definition of the Vue instance.

From the documentation:

The script must export a Vue.js component options object. Exporting an extended constructor created by Vue.extend() is also supported, but a plain object is preferred.


You are currently only exporting { name: 'app' }, which is why Vue can't find the show method.

Your <script> section should look like this:

<script>
  export default {
    name: 'app',
    data() {
      return { n: 0 }
    },
    methods: {
      show: function(event) {
        targetId = event.currentTarget.id;
        alert('click')
      }
    }
  }
</script>

Note also that the data property of the object exported needs to be a function returning the data properties. See the "Why does data need to be a function" section of Vue's Common Beginner Gotchas page.

查看更多
登录 后发表回答