未在实例上定义的Nuxtjs属性或方法

时间:2019-04-09 11:04:55

标签: vue.js nuxt.js

我正在尝试获取一个计数器,将nuxtjs模板中的变量计数器加1。不知道这是怎么回事:

<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>

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

尝试以下操作:

<template>
  ...
  <button @click="test(1)">Add 1</button>
  ...
</template>

<script>
...
methods: {
  test(count) {
    this.counter += count;
    console.log(this.counter)
  }
}
...