vue.js - 使用 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 中的名称值分配给输入字段?
解决方案
watcher可能是你需要的
export default {
// ...
watch: {
'$store.getters.getUser'(user) {
this.name = user.name;
},
},
}
推荐阅读
- google-cloud-automl - 有没有办法增加 AutoML 自然语言处理中要训练的标签数量?
- amazon-web-services - AWS 如何让 ASG 始终使用最新的 AMI?
- c# - 非静态方法在连接两个表时需要一个目标
- qt - apt-get 在 bitbaking meta-toolchain-qt5 时返回 100
- javascript - PHP - 抓取 javascript 网站
- qt - 即使存在,也找不到或加载 Qt 平台插件“windows”
- jquery - 未捕获的 TypeError:无法读取 null 的属性“错误”
- magnolia - 如何在 Magnolia CMS 的资产应用程序中查看文件夹的标识符?
- javascript - 将 react-testing-library 添加到项目时遇到问题 - TypeError: Cannot read property 'then' of undefined
- c# - 具有嵌套接口的自定义 JsonConverter