vue.js - 如何检查是否加载了 JSON 数据
问题描述
我使用 axios 在 vuex 中获取我的 JSON 文件,以便在多个组件上使用获取的数据。问题是我的页面在所有数据加载之前呈现。以下内容有效,因为我将渲染延迟了 2 秒,如果没有此超时,则会导致错误。我想以正确的方式做到这一点,但不知道该怎么做。
商店.JS
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
poss: null
},
getters: {
NAME: state => {
return state.name
},
POSS: state => {
return state.poss
}
},
mutations: {
SET_POSS : (state,payload) => {
state.poss = payload
},
ADD_POSS : (state,payload) => {
state.poss.push(payload)
},
},
actions:{
GET_POSS : async (context,payload) => {
let { data } = await axios.get("json/poss.json")
context.commit('SET_POSS',data)
},
SAVE_POSS : async (context,payload) => {
let { data } = await axios.post("json/poss.json")
context.commit('ADD_POSS',payload)
}
}
});
组件.VUE
module.exports = {
mounted:function(){
var self = this;
setTimeout(function () {
self.mkPageload()
}, 2000);
},
methods: {
mkPageload: function(){
let positions = this.$store.getters.POSS.pos
Object.keys(positions).forEach(key => {
// rendering
}
}
}
}
期望的结果是页面仅在 JSON 文件中的所有数据都已加载后才呈现。
解决方案
有几种方法可以解决这个问题。
您可以在组件中使用等待/异步。
async mounted () { await userStore.getAll() // access getter and render },
您可以观看 vuex 变量(可以在没有异步的情况下完成,但我喜欢添加它们)
async mounted () { await userStore.getAll() }, computed: { ...mapGetters('users') }, watch: { users(newValue, oldValue) { .... // render } }
不要忘记导入 mapGetters:https ://vuex.vuejs.org/guide/getters.html
推荐阅读
- css - MaterializeCSS 自动完成编辑 css
- python - 通过 Python 将记录插入 Teradata 表的问题
- tags - 通过标签运行 Nightwatch 测试,运行套件中的所有测试
- javascript - VueJs - 承诺返回但重定向不会发生
- assembly - RISC访问地址大于最大整数寄存器
- string - Scala:提取特定字符之前的单词
- ruby-on-rails - 无法从 camt_parser rails gem 获取 iban
- javascript - 是否可以获取 WASM 文件并返回 JS 文件?
- r - 计算R中行中的连续值
- javascript - 如何在 p5.js 中实现用户交互?我知道 p5 本身不支持交互,但有没有办法我可以自己编写?