반응형
(Vue) 비동기/대기 모드를 사용한 RouteUpdate 전?
let fetchData = async function() {
return $.get("https://jsonplaceholder.typicode.com/todos/1");
}
Vue.use(VueRouter);
const cComponent = {
data() {
return {
fetchedData: null
}
},
template: `<div>{{$route.params.id+': '}}{{fetchedData}}</div>`,
async beforeRouteEnter(to, from, next) {
let data = await fetchData();
next(vm => vm.fetchedData = data);
},
async beforeRouteUpdate(to, from, next) {
console.log("beforeRouteUpdate");
let data = await fetchData();
this.fetchedData = data;
next();
}
}
const routes = [{
path: "/path/:id",
component: cComponent,
}]
const router = new VueRouter({
mode: "history",
routes,
})
const app = new Vue({
el: "#app",
router,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src=" https://unpkg.com/vue-router@3.5.1/dist/vue-router.js"></script>
<div id="app">
<router-link to="/path/1">An URL</router-link>
<router-link to="/path/2">Another one</router-link>
<router-link to="/path/3">And another one</router-link>
<router-view :key="$route.path"></router-view>
</div>
서버에서 데이터를 검색하는 가져오기 기능:
let fetchPage = async (route) => {
return $.get('route');
}
이것은 나의 것이다.beforeRouteUpdate
항법 가드.fetchedData
Vue 인스턴스의 속성(사전 데이터 옵션으로 선언됨)은 변경되지 않는다.
async beforeRouteUpdate(to, from, next) {
this.fetchedData = await fetchPage(to.path);
//fetchData is not changed while changing route param
next();
}
그next()
콜백은 마지막에 활성화되지만(URL은 변경된다)this.fetchedData
드라마들.null
Vue DevTools(초기화 값)에서
반면에, 만약 내가 같은 일을 한다면.async/await
에beforeRouteEnter
훅, 모든 게 완벽하게 작동해
async beforeRouteEnter(to, from, next) {
let data = await fetchPage(to.path);
next(app => app.fetchedData = data); //fetchedData has fetched data as supposed.
},
나는 교체를 시도했다.this
와 함께app
의 경우와 마찬가지로beforeRouteEnter
훅. 하지만 아직 성과가 없다.
제가 무엇을 빠뜨리고 있나요?이게 가드 훅으로 하는 게 가장 좋은 연습인데 어떻게 하면 더 잘 쓸 수 있을까?(ignore)Exception
취급 부품)
업데이트됨: StackOverflow의 코드 조각에 대한 SPA 환경은 완벽하지 않기 때문에 내가 제공한 JS(여기)를 사용해 보십시오.같은 문제가 있지만 나는 단순화했다.
버전
부에 2.6
부에로터 3.5
참조URL: https://stackoverflow.com/questions/69835022/vue-beforerouteupdate-with-async-await
반응형
'programing' 카테고리의 다른 글
유닛 테스트에서 jest와 함께 부트스트랩 vue 구성 요소의 존재 여부를 테스트하는 방법? (0) | 2022.04.08 |
---|---|
Python에서 pathlib가 있는 파일 복사 (0) | 2022.04.08 |
python2에서 drit.items()와 drit.iteritems()의 차이점은 무엇인가? (0) | 2022.04.08 |
ReactNative 앱에서 EXPO_DEBUG 값을 설정하는 위치? (0) | 2022.04.08 |
Vue.js에게 강제로 재장전/재장전할 수 있는가? (0) | 2022.04.08 |