programing

작업 vuex 내의 vue 리소스에 액세스할 수 없음

javaba 2022. 8. 1. 23:24
반응형

작업 vuex 내의 vue 리소스에 액세스할 수 없음

여러분, 저는 vuex측에서 제 액션에서 요청을 하려고 하는데, 다음과 같은 오류가 나타납니다.

Cannot read property '$http' of undefined

vue-resource를 main.files 내에서 다음과 같이 설정합니다.

import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import App from './App.vue'
import {routes} from './routes';
import {store} from './store/store';
import VModal from 'vue-js-modal'

Vue.use(VModal)
Vue.use(VueResource);
Vue.use(VueRouter);

const router = new VueRouter({
  routes
});

new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

그 후 스토어에서:

addStyle(state,newStyleObj) {
    console.log(newStyleObj);
    var vm = this;
    this.$http.post('http://localhost:16339/api/Styles/PostStyle/', newStyleObj)
        .then(response => {
            state.tableStyles = response.body;
            console.log(state.tableStyles)
            console.log(response.body)
        }, error => {
            console.log(error);
        });
}

도움이 필요하신가요?

import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

const axiosInstance = axios.create({
    baseURL: '',
    withCredentials: true,
})

Vue.prototype.$axios = axiosInstance
Vuex.Store.prototype.$axios = axiosInstance

난 이거면 돼.

에 액세스 할 수 있게 되었습니다.this.$axiosVue와 Vuex에 있습니다.

이를 사용하여 스토어에서 Vue 인스턴스에 액세스할 수 있습니다._vm.

this._vm.$http.post()

다음은 이 문제에 대한 적절한 설명입니다.$httpvuex https://stackoverflow.com/a/42571288/6355502 에서는 액세스 할 수 없습니다.

상태는 돌연변이에 의해서만 바뀔 수 있습니다.행동하지 않는다.상태를 바꾸기 위해 행동 내부에서 돌연변이를 저지르세요.

어젯밤에도 같은 시도를 했는데 돌연변이를 일으키는 동작에서 비동기 페치를 실행하도록 강요하는 오류 메시지가 떴습니다.돌연변이로 비동기 작업을 수행할 수 없으며 동작 상태도 변경할 수 없으므로 코드를 분할해야 합니다.

// in actions
addStyle ({ commit, state }, newStyleObj) {
    console.log(newStyleObj);
    var vm = this;
    this.$http.post('http://localhost:16339/api/Styles/PostStyle/', newStyleObj)
        .then(response => {
            commit("setTableStyles", response.body);
            console.log(state.tableStyles)
            console.log(response.body)
        }, error => {
            console.log(error);
        });
}

// in mutations
setTableStyles(state, payload){
state.tableStyles = payload; // or state.tableStyles.push(...payload) if tableStyles is an Array 
}

외부 vue 인스턴스(store이 경우)의 사용Vue.http(달러 기호 없음), 내부 인스턴스 사용this.$http.

자세한 내용은 github에서 확인할 수 있습니다.

와의 공리에 대한 접근Vue.prototype.$http

login({commit}, loginFormData) {
            return new Promise((resolve, reject) => {
                commit('auth_request');
                Vue.prototype.$http({url: '/user/login', data: loginFormData, method: 'POST'})
                    .then(resp => {
                        const token = resp.data.data.token;
                        const user = resp.data.data.profile;
                        localStorage.setItem('token', token);
                        localStorage.setItem('user', JSON.stringify(user));
                        Vue.prototype.$http.defaults.headers['Authorization'] = 'Bearer ' + token;
                        this.state.user = JSON.parse(localStorage.getItem('user')) || '';
                        this.state.token = localStorage.getItem('token') || '';
                        commit('auth_success', {token, user});
                        resolve(resp)
                    })
                    .catch(err => {
                        commit('auth_error');
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        reject(err)
                    })
            })
        },

이 방법으로 vue 속성 액세스 시도this._vm.$yourDesiredPropertyName예를들면this._vm.$httpvue 인스턴스에 올바르게 등록된 모든 속성에 액세스할 수 있습니다.

언급URL : https://stackoverflow.com/questions/45633408/cant-access-vue-resource-inside-action-vuex

반응형