0
votes

I have a vuex in module mode that fetching the data of a user:

store/modules/users.js

import axios from "axios";

export const state = () => ({
  user: {}
});

// Sets the values of data in states
export const mutations = {
  SET_USER(state, user) {
    state.user = user;
  }
};

export const actions = {
  fetchUser({ commit }, id) {
    console.log(`Fetching User with ID: ${id}`);
    return axios.get(`${process.env.BASE_URL}/users/${id}`)
      .then(response => {
        commit("SET_USER", response.data.data.result);
      })
      .catch(err => {
        console.log(err);
      });
  }
};

// retrieves the data from the state
export const getters = {
  getUser(state) {
    return state.user;
  }
};

then on my template pages/users/_id/index.vue

<b-form-input v-model="name" type="text"></b-form-input>

export default {
  data() {
    return {
      name: ""
    }
  },
  created() {
    // fetch user from API
    this.$store.dispatch("fetchUser", this.$route.params.id);
  }
}

Now I check the getters I have object getUser and I can see the attribute. How can I assign the name value from vuex getters to the input field?

2

2 Answers

2
votes

watcher is probably what you need

export default {
  // ...
  watch: {
    '$store.getters.getUser'(user) {
      this.name = user.name;
    },
  },
}
-1
votes

While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here

  computed: {
    user(){
        return this.$store.getters.getUser
    }
  }

Then access name via {{user.name}} or create a name computed property

  computed: {
    name(){
        return this.$store.getters.getUser.name
    }
  }

Edit: fiddle as example https://jsfiddle.net/uy47cdnw/

Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.