Axios.post, Axios.all & Vue-router 쿼리스트링 변경하기

김승우·2021년 1월 27일
0

Vue.js 강의 내용 정리

목록 보기
10/15
post-thumbnail

Axios post 요청 보내기

: https://xn--xy1bk56a.run/axios/guide/usage.html#post-%EC%9A%94%EC%B2%AD

axios.post('url', data);

Axios 멀티(여러개) 요청 보내기

: https://xn--xy1bk56a.run/axios/guide/usage.html#post-%EC%9A%94%EC%B2%AD

axios.all([]);

axios.create()로 만든 인스턴스는 all() 메소드를 사용할 수 없다.

: https://github.com/axios/axios/issues/2890

axios.all async await으로 사용하기

: https://www.pluralsight.com/guides/all-need-to-know-about-axios

export const fetchMovieDetail = async (id) => {
    const [movieCredits, movieData] = await axios.all([
        fetchMovieCredits(id),
        fetchMovie(id),
    ]);

    const result = {
        cast: movieCredits.data.cast,
        crew: movieCredits.data.crew,
        ...movieData.data,
    };

    return result;
};

axios.all의 인자로 배열을 전달하고, 리턴도 배열을 통해 각 api 요청의 response 객체를 받을 수 있다.

😎 Vue에서 현재 라우트 경로는 유지하고, 쿼리스트링 혹은 url 파라미터만 변경하기

: https://stackoverflow.com/questions/40382388/how-to-set-url-query-params-in-vue-with-vue-router/40394184

this.$router.replace({
	path: this.$route.path,
	query: {
		q1: q1,
	}
})

$router.replace()는 $router.push()와 다르게 히스토리 스택을 쌓지 않는다. https://router.vuejs.org/kr/guide/essentials/navigation.html#router-replace-location

✨✨ $router.replace()로 같은 경로, 파라미터 혹은 쿼리 스트링으로 이동했을 때 발생하는 NavigationDuplicated 에러 핸들링하기.

this.$router.replace()
.catch(err => console.error(err));

this.$router.push()
.catch(err => console.error(err));

이때, 발생한 에러 정보를 가진 에러 객체를 .catch()를 이용해서 받을 수 있다.

const path = `/products/${id}`
if (this.$route.path !== path) this.$router.push(path)
  • 😎 이번 프로젝트에서는 movieId 쿼리를 변경하므로, $route.query값이 동일한지 체크해서, 페이지를 이동하는 로직을 추가했다.
const currentQuery = this.$route.query;

if (!!Object.keys(currentQuery).length) {
  // movieId 쿼리가 같은 경우
  if (currentQuery.movieId == this.movieId) {
    console.log(
      "movieId값이 동일하여 페이지를 이동하지 않습니다."
    );
    return;
  }
  //  movieId 쿼리가 다른 경우
  else {
    // 현재 라우트 경로를 유지하면서, 쿼리스트링만 변경하기
    return this.$router.replace({
      path: this.$route.path,
      query: {
        movieId: encodeURIComponent(this.movieId),
      },
    });
  }
}

Vue input 입력 길이 제한

<textarea
	name="contents"
	id="contents"
	rows="5"
	v-model="contents"
	maxlength="10"
	oninput="javascript: if(this.value.length > this.maxLength) { this.value = this.value.substr(0, this.maxLength); }"
></textarea>
profile
사람들에게 좋은 경험을 선사하고 싶은 주니어 프론트엔드 개발자

0개의 댓글