开发者问题收集

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

2019-04-09
1171

我试图让计数器将 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>
2个回答

这里有一个解决方案:

  • 引用计数器为 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>

在此处实时查看

James Whiteley
2019-04-09

尝试以下操作:

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

<script>
...
methods: {
  test(count) {
    this.counter += count;
    console.log(this.counter)
  }
}
...
Sajib Khan
2019-04-09