我有一个商店,用于存储对象数组。我试图访问该数组到组件中。但是我无法访问它。没有错误弹出到控制台。但是,当我尝试console.log()时,它显示了一个空数组。
我尝试打印store.js本身中的数据。它显示数据正在存储在商店中。
代码如下:
store.js
appsData: [],
mutations: {
storeAppsData(state, data) {
state.appsData = data;
}
},
getters: {
appsData: state => {
return state.appsData
}
},
actions: {
getAppsData(context) {
return new Promise((resolve, reject) => {
axios.get('http://localhost/phoenix/index.php/v1/menu', {
headers: {
'Content-Type': 'application/json'
},
auth: {
username: 'data.simulation@makeadiff.in',
password: 'pass'
}
}).
then(response => {
context.commit('storeAppsData', response.data.data.menu)
console.log(this.state.appsData)
resolve(response); // Let the calling function know that http is done. You may send some data back
}).catch(error => {
reject(error);
})
})
}
}
SubAppsRenderer.vue:
<template lang="html">
<CardRenderer :render-data="valArr" />
</template>
<script lang="js">
import CardRenderer from './CardRenderer'
export default {
name: 'SubAppsRenderer',
components: {
CardRenderer
},
props: [],
data() {
return {
valArr: []
}
},
let key = this.findLastPath()
mounted() {
console.log(this.$store.getters.appsData)
let value = this.$store.getters.appsData.filter((elem) => {
if(elem.name == key) return elem
})
if (value && value.length > 0)
this.valArr = value[0].apps
},
methods: {
findLastPath() {
let url = window.location.pathname.split("/").slice(-1)[0];
url = url.replace('%20', " ")
return url
}
},
computed: {
}
}
</script>
<style scoped >
</style>
CardGrouper.vue
<template lang="html">
<div class="full" >
<div>
<CardRenderer :renderData=this.apps />
</div>
</div>
</template>
<script>
import CardRenderer from "./CardRenderer.vue"
export default {
name: 'CardGrouper',
components: {
CardRenderer
},
props: [],
mounted() {
this.$store.dispatch('getAppsData').
then((response ) => {
this.apps = response.data.data.menu
}).
catch(() => {
})
},
data() {
return {
apps: []
}
},
methods: {
},
computed: {
}
}
</script>
<style scoped >
.full{
width: 100vw;
height: 90vh;
}
</style>
我如何使此代码起作用。
如何访问SubAppsRenderer.vue
组件中的数据?
答案 0 :(得分:0)
appsData: [],
应该在vuex中处于状态。
const state = {
appsData: []
};
,然后在尝试记录它的操作中,您正在通过上下文对其进行访问
console.log(context.state.appsData);
答案 1 :(得分:0)
不返还诺言。 Axios呼叫基于承诺。 返回axios.get,然后返回您的响应,然后从那里链接以获取您的响应。
getAppsData(context) {
return axios.get('http://localhost/phoenix/index.php/v1/menu', {
headers: {
'Content-Type': 'application/json'
},
auth: {
username: 'data.simulation@makeadiff.in',
password: 'pass'
}
}).
then(response => {
context.commit('storeAppsData', response.data.data.menu)
console.log(this.state.appsData)
return response // Let the calling function know that http is done. You may send some data back
}).catch(error => {
console.log('err',error)
})
}