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

时间:2019-01-03 09:06:42

标签: vue.js nuxt.js vuex-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;
  }
};

然后在我的模板页面/用户/_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获取器将 name 值分配给输入字段?

2 个答案:

答案 0 :(得分:2)

watcher可能是您需要的

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

答案 1 :(得分:0)

尽管Jacob的答案不一定正确,但最好使用计算属性。您可以了解有关here

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

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

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

编辑:以小提琴为例https://jsfiddle.net/uy47cdnw/

Edit2:请不要不要,如果要通过该输入字段对对象进行突变,则应使用提供的链接Jacob。

相关问题