首页 > 解决方案 > 使用 Vuex 存储模块为输入字段设置值

问题描述

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

存储/模块/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;
  }
};

然后在我的模板页面/用户/_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的吸气剂,我可以看到该属性。如何将 vuex getter 中的名称值分配给输入字段?

标签: vue.jsnuxt.jsvuex-modules

解决方案


watcher可能是你需要的

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

推荐阅读