【问题标题】:VueJS TypeError cannot read property ofVueJS TypeError 无法读取的属性
【发布时间】:2019-04-14 13:25:23
【问题描述】:

好的,所以我可能已经有 2 年多没有使用 Vue 了,我正在给自己复习一下。问这么简单的问题我觉得很傻,但我就是不知道我做错了什么。我有一个简单的反例,我正在调用 v-on:click(调用我的方法)。称为 counter 的方法只是执行 this.count++。我验证了该方法有效,因为我可以在其中调用 console.log 或 alert 而没有问题。但是当我尝试增加计数器时,它返回“v-on 处理程序中的错误:“TypeError:无法读取未定义的属性'count'”。我的源代码如下:

<template lang="pug">
    b-container(id="cont")
        b-button(v-on:click="counter") Click Me
        p {{count}}

</template>

<script>
    export default {
        data: () => {
            return {
                count: 0
            }        
        },
        methods: {
            counter: () => {
                this.count++
            }
        }
        
    }
</script>

<style>
#cont {
   margin-top: 10px
}
</style>

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    我认为这与您使用箭头函数来定义您的方法这一事实有关,因此请尝试以下操作:

    <script>
    export default {
        data(){
            return {
                count: 0
            }        
        },
        methods: {
            counter(){
                this.count++
            }
        }
    
    }
    </script>
    

    因为箭头函数未绑定到this,所以this 将在箭头函数内部未定义。

    【讨论】:

      【解决方案2】:

      试试这个:

      data() {
          return {
             count: 0
          }
      }
      

      例如,没有将其作为方法。

      【讨论】:

        【解决方案3】:

        如果你愿意使用带箭头的版本,可以这样使用:

        data: () => {( counter: 0 )},

        否则参考前面的答案=)

        【讨论】:

          猜你喜欢
          • 2021-12-08
          • 2020-11-08
          • 2017-09-16
          • 2020-08-27
          • 2021-12-28
          • 1970-01-01
          • 1970-01-01
          • 2019-11-26
          • 2020-11-23
          相关资源
          最近更新 更多