[Vuejs]-Cannot read component data within v-for scope

1đź‘Ť

âś…

Change :placeholder="this.whatever" to :placeholder="whatever". You don’t need to use this there because Vue recognize that you want to access its data or computed values. This doesn’t work because this in the loop is something else.

Look at this code snippet below (I had to change some things to reproduce your problem):

var app = new Vue({
  el: '#app',
  data() {
    return {
      whatever: 'this is a string',
      userShouldSignup: false,
      parameters: {
        email: {
          label: 'Enter email',
          type: 'email',
          value: '',
        },
        password: {
          label: 'Enter password',
          type: 'password',
          value: '',
        },
        confirmPassword: {
          label: 'Confirm password',
          type: 'password',
          value: '',
        },
      },
    }
  },
  computed: {
    inputFields() {
      return this.userShouldSignup ? [
        this.parameters.email,
        this.parameters.password,
        this.parameters.confirmPassword,
      ] : [
        this.parameters.email,
        this.parameters.password,
      ];
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <div class="my-1" v-for="field in inputFields" :key="field.key">
    <div>
      <input type="text" :placeholder="whatever" required/>
    </div>
  </div>
  <input :placeholder="whatever" required/>
</div>
👤Dawid Loranc

1đź‘Ť

It’s not working because “this” is pointing to “field” (loop), and the “field” doesn’t have a “whatever” variable.

You just need to remove “this” keyword. You don’t need it at all when access the variables from “data”

👤Duy Anh

Leave a comment