Vuejs screwing up the selected option in a select component

Posted 2 years ago by tiagomatosweb

Hi all, I'm passing data from parent to child component in order to select a default option in a select element. This select, which is in the child component, is populated by the child component itself. The default value should come from the parent.

So, once everything renders the select is not marked the default option according to the parent value, also, the parent value is being deleted.

App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <h1></h1>

    <h4>Example 1</h4>
    <user :account="account"></user>
  </div>
</template>

<script>
import user from './User.vue'

export default {
  name: 'app',

  components: {user},

  created() {
    this.getAccount();
  },

  data () {
    return {
      account: {
        id: '',
        name: ''
      }
    }
  },

  methods: {
    getAccount() {
      this.$http.get('account.json')
      .then((res) => {
        this.account.id = res.body.id
      })
    }
  }
}
</script>

User.vue

<template>
  <div>
    {{ account }}<br>
    <select v-model="account.id">
    <option value="">Choose</option>
    <option v-for="(user, index) in users" :value="user.id">{{ user.name }}</option>
  </select>

  </div>
</template>

<script>
export default {
  props: {
    account: {
      type: Object,
      required: true
    }
  },

  created() {
    this.getUsers();
  },

  data() {
    return {
      users: [],
    }
  },

  methods: {
    getUsers() {
      this.$http.get('https://jsonplaceholder.typicode.com/users')
      .then((res) => {
        this.users = res.body;
      })
    }
  }
}
</script>

I made a package using https://github.com/vuejs-templates/webpack in order to facilitate your help. You can download the package here

Please sign in or create an account to participate in this conversation.