VueJs를 다른 컴포넌트(동일한 Axios에서 다른 컴포넌트로)
두 개의 다른 컴포넌트가 있으며 각각 Axios의 응답을 받습니다.단, 각 컴포넌트의 데이터를 개별적으로 취득하고 싶지 않습니다.그건 옳지 않아, 그러면 구성 요소들이 분리되고...
갱신 3
코드를 변경했는데 아직 문제가 좀 있어요.나는 Vuex와 악시오스 콜을 하고 있다.Store.js
컴포넌트에 Import합니다.아래와 같습니다.
이것은 my store.js 컴포넌트입니다.
import Vue from "vue";
import Vuex from "vuex";
var actions = _buildActions();
var modules = {};
var mutations = _buildMutations();
const state = {
storedData: []
};
Vue.use(Vuex);
const getters = {
storedData: function(state) {
return state.storedData;
}
};
function _buildActions() {
return {
fetchData({ commit }) {
axios
.get("/ajax")
.then(response => {
commit("SET_DATA", response.data);
})
.catch(error => {
commit("SET_ERROR", error);
});
}
};
}
function _buildMutations() {
return {
SET_DATA(state, payload) {
console.log("payload", payload);
const postData = payload.filter(post => post.userId == 1);
state.storedData = postData;
}
};
}
export default new Vuex.Store({
actions: actions,
modules: modules,
mutations: mutations,
state: state,
getters
});
다음으로 Import하는 중Average
요소.
import store from './Store.js';
export default {
name:'average',
data(){
return{
avg:"",
storedData: [],
}
},
mounted () {
console.log(this.$store)
this.$store.dispatch('fetchDatas')
this.storedData = this.$store.dispatch('fetchData')
},
methods: {
avgArray: function (region) {
const sum = arr => arr.reduce((a,c) => (a += c),0);
const avg = arr => sum(arr) / arr.length;
return avg(region);
},
},
computed: {
mapGetters(["storedData"])
groupedPricesByRegion () {
return this.storedData.reduce((acc, obj) => {
var key = obj.region;
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj.m2_price);
return acc;
}, {});
},
averagesByRegion () {
let arr = [];
Object.entries(this.groupedPricesByRegion)
.forEach(([key, value]) => {
arr.push({ [key]: Math.round(this.avgArray(value)) });
});
return arr;
},
}
}
콘솔에 저장된 데이터를 볼 수 있습니다.하지만 오류도 있습니다.데이터를 제대로 전달할 수 없다myComponent
https://i.stack.imgur.com/J6mlV.png
vuex를 사용하여 데이터를 배포하지 않으려면 eventBus를 사용해 보십시오.이벤트 및 이 이벤트의 다른 컴포넌트 @emit에서 데이터를 가져오면 eventBus를 사용해 보십시오.
발생한 오류를 해결하기 위한 절차는 다음과 같습니다.
Vue 인스턴스가 초기화되어 있는 파일 내에 스토어 파일을 Import합니다.
// Assuming your store file is at the same level
import store from './store';
내부에 Vue 인스턴스 내에 스토어 개체를 추가합니다.
function initApp(appNode) {
new Vue({
el: appNode,
router: Router,
store // ES6 sytax
});
}
이제 모든 컴포넌트에서 스토어에 액세스할 수 있습니다.
업데이트: 두 번째 오류의 경우
컴포넌트 내부에서 데이터를 변경하는 대신 내부에서 데이터를 변경합니다.mutation
스토어에서 동일한 방법을 사용하는 다른 컴포넌트에서는 동일한 로그인을 작성하지 않기 때문입니다.
이런 이유로,
computed: {
...mapGetters(["storedData"]),
anotherFunction() {
// Function implementation.
}
}
당신의 돌연변이 안에 데이터를 세팅합니다.
SET_DATA(state, payload) {
console.log("payload", payload);
state.storedData = payload;
}
getter 내부에서는 계산된 속성 내에서 수행하던 작업을 수행할 수 있습니다.
storedData: function(state) {
const postData = state.storedData.filter(post => post.userId == 1);
return postData;
}
Vuex 공식 문서
여기 작업 코드와 상자입니다.
이게 도움이 됐으면 좋겠네요!
언급URL : https://stackoverflow.com/questions/55391493/from-same-axios-to-different-components-vuejs
'programing' 카테고리의 다른 글
Vue.js - 동적으로 생성한 정의되지 않은 img 소스 변경 (0) | 2022.06.09 |
---|---|
다른 Vue 프로젝트 내에서 Vue 웹 컴포넌트(Vue-CLI 3에서 생성)를 사용하는 방법 (0) | 2022.06.09 |
Vuex - 첫 번째 getter 호출 시 API에서 데이터를 로드한 후 상태에서 로드합니다. (0) | 2022.06.09 |
Input Stream 복제 방법 (0) | 2022.06.09 |
Vue에서 계산된 속성을 사용하여 v-bind 이미지 src를 만듭니다.JS (0) | 2022.06.07 |