【问题标题】:Nuxtjs property or method not defined on instanceNuxtjs 属性或方法未在实例上定义
【发布时间】:2019-08-30 15:52:39
【问题描述】:

我正在尝试让一个计数器将 1 添加到 nuxtjs 模板中的变量计数器。不知道这里发生了什么:

<template>
  <div class="container">
    <div>
      <h1>London Weather</h1>
      <div id="example-1">
        <button @click="test()">Add 1</button>
        <p>The button above has been clicked {{ counter }} times.</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data: {
    counter: 0
  },
  methods: {
    test: function(counter) {
      this.counter += 1
      console.log(counter)
    }
  },
}
</script>

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    这里有一个解决方案:

    • 引用计数器为this.counter
    • data 是一个函数,它应该返回你需要的任何数据
    • test 不需要带参数,因为您只是更改组件的状态,而不是修改您传入的某些参数
    <template>
      <div class="container">
        <div>
          <h1>London Weather</h1>
          <div id="example-1">
            <button @click="test">Add 1</button>
            <p>The button above has been clicked {{ counter }} times.</p>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    import axios from 'axios'
    
    export default {
      data() {
        return {
          counter: 0
        }
      },
      methods: {
        test: function() {
          this.counter += 1
          console.log(this.counter)
        }
      }
    }
    </script>
    

    See it live here

    【讨论】:

    • 您不需要在模板中的柜台上使用“this”,但在其他两点上向我 +1。
    • 啊,好点子,我现在改一下。我总是搞不清楚在哪里放置this. 以及在哪里忽略它。
    【解决方案2】:

    尝试以下方法:

    <template>
      ...
      <button @click="test(1)">Add 1</button>
      ...
    </template>
    
    <script>
    ...
    methods: {
      test(count) {
        this.counter += count;
        console.log(this.counter)
      }
    }
    ...

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 2021-07-17
      • 2017-08-28
      • 1970-01-01
      • 2019-01-10
      • 2021-09-02
      • 2020-07-14
      • 2019-04-08
      • 2017-06-16
      相关资源
      最近更新 更多