Home > Net >  Variable set in fetch() becomes empty in method() NuxtJS
Variable set in fetch() becomes empty in method() NuxtJS

Time:09-10

I have a simple NuxtJS page. My part of code:

<template>
  <div>
    <button @click="btnClick">
      Click
    </button>
  </div>
</template>

<script>
export default {
  name: 'TestPage',
  data () {
    return {
      testArray: []
    }
  },
  fetch () {
    // eslint-disable-next-line dot-notation
    this.testArray['key'] = '123321'
    console.log('Log1========================')
    console.log(this.testArray)
    console.log('====================================')
  },
  methods: {
    btnClick () {
      console.log('Log2========================')
      console.log(this.testArray)
      console.log('====================================')
    }
  }
}
</script>

So, when I am loading this page or reload page, I have got in Console:

[Log] Log1========================
[Log] [ key: '123321' ]
[Log] ====================================

but when I click on a button, array is empty:

[Log] Log2========================
[Log] [] (0)
[Log] ====================================

I am using Nuxt 2.15.8. I can't understand, what's problem can be, because if my memory serves me right, I have done the same things many times, and there was no problems with this.

CodePudding user response:

You're actually defining testArray as an object at your line this.testArray['key'] = '123321' you can either change your definition of testArray to an object testArray: {} or add '123321' to your array with testArray.push('123321')

  • Related