使用 Vuex 存储模块为输入字段设置值

Setting value to input field using Vuex store modules

我有一个模块模式的 vuex 可以获取用户的数据:

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;
  }
};

然后在我的模板上 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);
  }
}

现在我检查我有对象 getUser 的 getter,我可以看到该属性。如何将 vuex getter 中的 name 值分配给输入字段?

watcher可能就是你需要的

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

虽然 Jacob 的答案不一定不正确,但最好使用计算 属性 代替。你可以阅读 here

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

然后通过 {{user.name}} 访问名称或创建计算的名称 属性

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

编辑:fiddle 例如 https://jsfiddle.net/uy47cdnw/

Edit2:请注意,如果您想通过该输入字段改变对象,您应该使用 link Jacob 提供的。