Navegación de enrutamiento VUE (inicio de sesión de intercepción de enrutamiento, permisos, restricciones de salto). Ciclo de vida de VUE: beforeRouteLeave

Requisito: después de que el usuario edite, si hay datos en el grupo, se le pedirá que los guarde al salir de la página.
Dado que una página no solo regresará, sino que también navegará a otras páginas, escribir la lógica en el botón de retorno por sí solo no puede cumplir con los requisitos. La navegación de enrutamiento puede hacerlo: referencia
de documento oficial

router.beforeEach((to, from, next) => {
    
    
  console.log(to);   // 即将要进入路由的对象
  console.log(from); // 当前导航要离开的路由对象
  console.log(next); // 调用next该方法,才能进入下一个路由
  next();
});

Código de ejemplo: archivo raíz del enrutador


import {
    
    MessageBox} from 'element-ui'
import store from '../store/index'
import Router from 'vue-router'
//..............
const router = new Router({
    
    ......})
//..............
router.beforeEach((to, from, next) => {
    
    
  let fromPath = from.fullPath==='/vocabulary/create'||from.fullPath==='/vocabulary/edit'
  let toPath = to.fullPath!='/vocabulary/create'&&to.fullPath!='/vocabulary/edit'
  let editTF = store.state.vocabulary.checkedList.length;
  // 来自这俩路由 去的不是这俩路由 且有编辑内容
  if(editTF&&fromPath&&toPath){
    
    
      MessageBox.confirm('您有编辑内容尚未保存,确认退出?', '提示', {
    
    
          confirmButtonText: '确定',
          type: 'warning',
          center: true,
      }).then(() => {
    
    
          store.commit(`vocabulary/coverCheckedList`,[]);
          next();
      }).catch(() => {
    
    
//         // next(false);
//         // router.replace(to.fullPath);
//         // router.push(to.fullPath)
//           // next(from.fullPath);
//           // abort();
        // router.back();
      });
    } else {
    
    
      store.commit(`vocabulary/setSearchModel`,{
    
    });
      store.commit(`vocabulary/setSearchModel_Page`,{
    
    });
      store.commit(`vocabulary/setCurTab`,true);
      next();
    } 
 })

Sin embargo, debido a la particularidad de mis necesidades, esto hará que el usuario haga clic en cancelar para entrar en un ciclo sin fin, y se han probado muchos métodos sin éxito.
Así que encontré otra forma de encontrar el ciclo de vida de VUE: beforeRouteLeave

    beforeRouteLeave(to,from,next){
    
    
        let fromPath = from.fullPath==='/vocabulary/create'||from.fullPath==='/vocabulary/edit'
        let toPath = to.fullPath!='/vocabulary/create'&&to.fullPath!='/vocabulary/edit'
        let editTF = this.$store.state.vocabulary.checkedList.length;
        // 来自这俩路由 去的不是这俩路由 且有编辑内容
        if(editTF&&fromPath&&toPath){
    
    
            this.$confirm('您有编辑内容尚未保存,确认退出?', '提示', {
    
    
                confirmButtonText: '确定',
                type: 'warning',
                center: true,
            }).then(() => {
    
    
                this.$store.commit(`vocabulary/coverCheckedList`,[]);
                next();
            }).catch(() => {
    
    
                return
            });
        } else {
    
    
            this.$store.commit(`vocabulary/setSearchModel`,{
    
    });
            this.$store.commit(`vocabulary/setSearchModel_Page`,{
    
    });
            this.$store.commit(`vocabulary/setCurTab`,true);
            next();
        } 
    }

Solución perfecta a las necesidades ~

Supongo que te gusta

Origin blog.csdn.net/Beatingworldline/article/details/120717962
Recomendado
Clasificación