IT이야기

vuex 스토어에서 vue-resource($ttp) 및 vue-router($route)를 사용하는 방법?

cyworld 2022. 3. 15. 20:46
반응형

vuex 스토어에서 vue-resource($ttp) 및 vue-router($route)를 사용하는 방법?

컴포넌트 대본에서 영화 디테일을 받기 전에.이 기능은 먼저 스토어의 영화 ID가 경로의 파라메타 영화 ID와 동일한지 여부를 확인한다.같은 경우 서버 API에서 동영상을 가져오지 않거나 서버 API에서 동영상을 가져오십시오.

잘 되고 있었다.하지만 지금은 가게의 변이로부터 영화의 세부사항을 얻으려고 노력하고 있다.하지만 나는 실수를 하고 있다.

검색되지 않은 TypeError: 정의되지 않은 속성 '$route'를 읽을 수 없음

부에루터 사용법($route)파람과 부에 닿다($http)vuex 저장소에 있는 서버 API에서 가져오시겠습니까?

store.js:

export default new Vuex.Store({
    state: {
        movieDetail: {},
    },
    mutations: {
        checkMovieStore(state) {
            const routerMovieId = this.$route.params.movieId;
            const storeMovieId = state.movieDetail.movie_id;
            if (routerMovieId != storeMovieId) {
                let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
                this.$http.get(url)
                    .then((response) => {
                        state.movieDetail = response.data;
                    })
                    .catch((response) => {
                        console.log(response)
                    });
            }
        },
    },
});

구성 요소 스크립트:

export default {
    computed: {
        movie() {
            return this.$store.state.movieDetail;
        }
    },
    created: function () {
        this.$store.commit('checkMovieStore');
    },
}

사용 방법$http또는$routervuex 스토어에서는 기본 vue 인스턴스를 사용해야 한다.나는 이것을 사용하는 것을 추천하지는 않지만, 실제 질문에 답한 후에 내가 추천하는 것을 추가하겠다.


당신 안에main.js또는 다음과 같은 vue 인스턴스를 생성하는 장소:

new Vue({ 
  el: '#app',
  router,
  store,
  template: '<App><App/>',
  components: {
    App
  }
})

아니면 비슷한 걸 더했을 수도 있지vue-router, 그리고vue-resource플러그 인들도.

이를 약간 수정하는 경우:

export default new Vue({ 
  el: '#app',
  router,
  store,
  template: '<App><App/>',
  components: {
    App
  }
})

나는 이제 이렇게 vuex 매장에서 그것을 수입할 수 있다.

//vuex store:
import YourVueInstance from 'path/to/main'

checkMovieStore(state) {
const routerMovieId = YourVueInstance.$route.params.movieId;
const storeMovieId = state.movieDetail.movie_id;
if (routerMovieId != storeMovieId) {
  let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
  YourVueInstance.$http.get(url)
    .then((response) => {
       state.movieDetail = response.data;
     })
     .catch((response) => {
       console.log(response)
     });
  }
}

그리고 오스티오의 대답에 따르면, 이 방법은action로서mutations비동기 처리를 위해 설계되지 않음.


이제 권장하는 방법으로 가는 겁니다.

  1. 당신의component에 접근할 수 있다route params그리고 그것을 에 제공한다.action.

    methods: {
      ...mapActions({
        doSomethingPls: ACTION_NAME
      }),
      getMyData () {
        this.doSomethingPls({id: this.$route.params})
      }
    }
    
  2. action그런 다음 추상화된 API 서비스 파일(읽기 )을 통해 호출을 수행하십시오.

    [ACTION_NAME]: ({commit}, payload) {
       serviceWhichMakesApiCalls.someMethod(method='GET', payload)
         .then(data => {
            // Do something with data
         })
         .catch(err => {
            // handle the errors
         })
    }
    
  3. 당신의actions일부 비동기 작업을 수행하여 결과를 a에 제공mutation.

    serviceWhichMakesApiCalls.someMethod(method='GET', payload)
         .then(data => {
            // Do something with data
            commit(SOME_MUTATION, data)
         })
         .catch(err => {
            // handle the errors
         })
    
  4. Mutations오직 당신만을 개조할 수 있어야 한다.state.

    [SOME_MUTATION]: (state, payload) {
       state[yourProperty] = payload
    }
    

: 엔드포인트 목록을 포함하는 파일, 테스트, 스테이징, 프로덕션 등 서로 다른 API 엔드포인트를 가진 배포 단계가 있는 경우 이 파일이 필요할 수 있음

export const ENDPOINTS = {
  TEST: {
    URL: 'https://jsonplaceholder.typicode.com/posts/1',
    METHOD: 'get'
  }
}

그리고 구현되는 메인 파일Vue.http서비스로서:

import Vue from 'vue'
import { ENDPOINTS } from './endpoints/'
import { queryAdder } from './endpoints/helper'
/**
*   - ENDPOINTS is an object containing api endpoints for different stages.
*   - Use the ENDPOINTS.<NAME>.URL    : to get the url for making the requests.
*   - Use the ENDPOINTS.<NAME>.METHOD : to get the method for making the requests.
*   - A promise is returned BUT all the required processing must happen here,
*     the calling component must directly be able to use the 'error' or 'response'.
*/

function transformRequest (ENDPOINT, query, data) {
  return (ENDPOINT.METHOD === 'get')
      ? Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query))
      : Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query), data)
}

function callEndpoint (ENDPOINT, data = null, query = null) {
  return new Promise((resolve, reject) => {
    transformRequest(ENDPOINT, query, data)
      .then(response => { return response.json() })
      .then(data => { resolve(data) })
      .catch(error => { reject(error) })
  })
}

export const APIService = {
  test () { return callEndpoint(ENDPOINTS.TEST) },
  login (data) { return callEndpoint(ENDPOINTS.LOGIN, data) }
}

queryAdder가 중요할 경우를 대비해서, 나는 이것을 URL에 매개 변수를 추가하는 데 사용하고 있었다.

export function queryAdder (url, params) {
  if (params && typeof params === 'object' && !Array.isArray(params)) {
    let keys = Object.keys(params)
    if (keys.length > 0) {
      url += `${url}?`
      for (let [key, i] in keys) {
        if (keys.length - 1 !== i) {
          url += `${url}${key}=${params[key]}&`
        } else {
          url += `${url}${key}=${params[key]}`
        }
      }
    }
  }
  return url
}

따라서 $store와 $route는 Vue 인스턴스의 속성이므로 Vuex 인스턴스 내에서 이러한 속성에 액세스할 수 없다.또한, 돌연변이는 당신에게 필요한 것이 행동이다.

  1. 돌연변이 => 주어진 상태와 일부 인수가 상태를 변이시키는 함수

  2. 작업 => http 호출과 같은 비동기 작업을 수행한 다음 결과를 돌연변이에 커밋

따라서 http를 발송하는 작업을 만드십시오.이것은 유사 코드라는 것을 명심해라.

//action in store
checkMovieStore(store, id) {
  return $http(id)
    .then(response => store.commit({ type: 'movieUpdate', payload: response })
}

//mutation in store
movieUpdate(state, payload) {
  //actually set the state here 
  Vue.set(state.payload, payload)
}

// created function in component
created: function () {
   return this.$store.dispatch('checkMovieStore', this.$route.params.id);
},

이제 당신이 만든 함수는 checkMovieStore 액션을 아이디와 함께 발송하고, http 호출이 완료되면 그 값으로 스토어를 업데이트한다.

vuex 스토어에서:

import Vue from 'vue'

Vue.http.post('url',{})

않음: 日반 vue 구성 요요요요요와:요다:::다:this.$http.post(...)

vuex 모듈(스토어 및 하위 모듈)에서 공리를 가져와 http 요청에 사용할 것을 적극 권장한다.

스토어 사용에서 vue 인스턴스에 액세스하려면 다음과 같이 하십시오.this._vm.
그러나 암레쉬의 조언대로 이런 것들을 사용하지 마십시오.$router화류로

참조URL: https://stackoverflow.com/questions/42560318/how-to-use-vue-resource-http-and-vue-router-route-in-a-vuex-store

반응형