programing

Vue-roouter 2는 경로를 변경하지만 보기를 업데이트하지 않는가?

prostudy 2022. 5. 3. 20:54
반응형

Vue-roouter 2는 경로를 변경하지만 보기를 업데이트하지 않는가?

다음을 사용하는 웹 사이트에 로그인 문제가 있는 경우:

  • Vue.js v2.0.3
  • vue-reason v2.0.1
  • vuex v0.8.2

routes.js간단한 인터셉터 설정이 있다.

router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!router.app.auth.isUserLoggedIn) {
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    } else {
        next()
    }
} else {
    next() // make sure to always call next()!
}

})

그리고 안에login.vue로그인에 대해서만 Google API를 사용한 후 로그인 페이지 로직을 처리한다. 나는 이것을 다음과 같이 부른다.

this.login(userData).then( 
    () => this.$router.push(this.redirectToAfterLogin), // Login success
    () => {} // Login failed
)


mounted: function(){
if (this.auth.isUserLoggedIn){
            // Let's just redirect to the main page
            this.$router.push(this.redirectToAfterLogins)
        }else{
            Vue.nextTick(() => {
                this.loadGooglePlatform()
            })}}


computed: {
        redirectToAfterLogin: function() {
            if (this.$route.query.redirect){
                return this.$route.query.redirect
            }else{
                return '/'
            }
        }
    }

라우터.js

var VueRouter = require('vue-router')

// Router setup
export const router = new VueRouter({
    linkActiveClass: "is-active",
    mode: 'history',
    saveScrollPosition: true,
    routes: [
        { path: '', name: 'root', redirect: '/home' },
        { path: '/login', name: 'login', meta: { loadingNotRequired: true }, component: require('./pages/login.vue') },
        { path: '/logout', name: 'logout', meta: { loadingNotRequired: true }, component: require('./pages/logout.vue') },
        { path: '/home', name: 'home', title: 'Home', redirect: '/home/random', component: require('./pages/home.vue'),
            children: [
                { path: 'random', name: 'random', meta: { requiresAuth: true }, title: 'Random', component: require('./pages/random.vue') }
            ]  
        }
    ]
})

// Redirect to login page if not logged In
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // this route requires auth, check if logged in
        // if not, redirect to login page.
        if (!router.app.auth.isUserLoggedIn) {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        } else {
            next()
        }
    } else {
        next() // make sure to always call next()!
    }
})

자, 여기this.login로그인한 사용자를 업데이트하기 위한 vuex 호출일 뿐.

로그인 후 URL이 /home으로 변경되지만 DOM은 업데이트되지 않는 경우!

DOM을 성공적으로 바꾼 유일한 방법은location.reload()그리고 그것은 내가 원하는 것이 아니다. 왜냐하면 그것은 나의 동적으로 로드된 G 스크립트를 헤드에서 잃어버리기 때문이다.

보기를 강제로 DOM으로 업데이트하려면 어떻게 해야 하는지 알고 싶으십니까?

참고: 이 작업은 사용자가 처음 로그인할 때만 수행되며 로그아웃했다가 다시 로그인할 경우 리디렉션은 정상임

구성요소를 재생성할 것이기 때문에 완벽한 해결책은 아닐 수 있지만 동일한 경로와 구성요소를 업데이트해야 할 경우 모든 경우에 효과가 있을 수 있다.

업데이트만 하면<router-view/>또는<router-view></router-view>와 함께

<router-view :key="$route.fullPath"></router-view>

Vue는 가능한 경우 구성 요소를 다시 사용한다.당신은 사용해야만 한다.beforeRouteUpdate동일한 구성요소를 사용하는 경로 스위치에 반응한다.

나는 "URL이 /home으로 변경되지만 DOM은 업데이트되지 않는다"라는 동일한 문제가 있다.
내 프로젝트에서, "전환"이라는 꼬리표가 문제를 조작했다.
도움이 되길 바래.

redirectToAfterLogin 기능을 이렇게 설정하여 매번 다시 계산하십시오.계산된 것은 사용된 v-모델이 변경된 경우에만 수정된다.함수 이름의 의미에 충실하기 위해, 나는 라우터 푸시를 안으로 설정하겠다.

login.vue :

mounted: function(){
   if (this.auth.isUserLoggedIn){
            // Let's just redirect to the main page
            // this.$router.push(this.redirectToAfterLogins)
            this.redirectToAfterLogins()
   }else{
            Vue.nextTick(() => {
                this.loadGooglePlatform()
            })
   }
},
// computed: {
methods: {
    this.login(userData).then( 
       // () => this.$router.push(this.redirectToAfterLogin), // Login success
       () => this.redirectToAfterLogin(), // Login success
       () => {} // Login failed
    ),
    redirectToAfterLogin: function() {

        if (this.$route.query.redirect){
            // return this.$route.query.redirect
            this.$router.push(this.$route.query.redirect)
        }else{
            // return '/'
            this.$router.push('/')
        }
    }
}

"하지만, 차이점은 계산된 속성이 종속성을 기반으로 캐시된다는 겁니다.계산된 속성은 그것의 의존성 중 일부가 변경된 경우에만 재평가된다.이는 메시지가 변경되지 않은 한, reverseMessage 계산 속성에 대한 다중 액세스는 기능을 다시 실행할 필요 없이 이전에 계산된 결과를 즉시 반환한다는 것을 의미한다."

메서드 대 계산 및 필터:

참조URL: https://stackoverflow.com/questions/40348177/vue-router-2-changes-route-but-does-not-update-the-view

반응형