ant-design-vue页面刷新

版权声明:转载请注明出处并附上原文链接,谢谢! https://blog.csdn.net/CODING_1/article/details/90524095

当侧边栏两个菜单引用同一个组件的时候,这时路由切换组件是不会重新渲染的,生命周期函数也不会执行,此时就需要将页面刷新。页面刷新有两种方法:一种在路由后面加上参数;另外一种是页面重定向到一个页面,然后再重定向回来。在vue-element-admin中花裤衩大神使用重定向的方法实现了页面的刷新,但是ant-design-vue-pro中就需要我们自己动手了,当然思路也是参考vue-element-admin中的重定向思路。
在这里插入图片描述
我们在表单中输入数据,在切换菜单时表单中的数据依旧存在。
实现思路:

  1. 点击切换菜单
  2. 先跳转至redirect页面
  3. 再由redirect页面重定向回目标路由

注意这里使用beforeRouteUpdate,如果使用方法(watch,beforeRouteLeave)会陷入死循环,因为每次路由改变都会重新调用方法执行,beforeRouteUpdate官网这么介绍的

beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
},

这与我们的需求简直不要太吻合,整体目录结构及代码如下:

├─config
│      defaultSettings.js
│      router.config.js // 需要修改--添加 redirect 路由
│
└─views
    │
    ├─redirect  // 新增页面
    │      Index.vue
    │
    ├─test // 新增测试模块
         Form.vue  // 路由引用的公共组件
         Index.vue // 代替默认的RouteView,主要为了执行beforeRouteUpdate

route.config.js

export const asyncRouterMap = [
  // 添加 redirect 路由
  {
    path: '/redirect',
    component: BasicLayout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path*',
        component: () => import('@/views/redirect/Index')
      }
    ]
  },
  {
  // 其他路由...
  // 引用同一个组件
  {
       path: '/test/form-a',
       component: () => import('@/views/test/Form'),
       ...
     },
     {
       path: '/test/form-b',
       component: () => import('@/views/test/Form'),
       ...
     }
  }

redirect 文件内容
Index.vue 此文件重定向回目标路由

<script>
export default {
  created() {
    const { params, query } = this.$route
    const { path } = params
    this.$router.replace({ path: '/' + path, query })
  },
  render: function(h) {
    return h() // avoid warning message
  }
}
</script>

test 文件夹
Index.vue,这个文件实现往redirect页面跳转

<script>
import {RouteView} from '@/layouts';
export default {
  extends: RouteView,  // 对RouteView进行扩展
  beforeRouteUpdate(to, from, next) {
    this.refreshView(to.fullPath);
  },
  methods: {
    refreshView(url) {
      url = url || this.$route.fullPath; 

      this.$nextTick(() => {
        this.$router.replace({
          path: '/redirect' + url
        })
      })
    }
  },
}
</script>

猜你喜欢

转载自blog.csdn.net/CODING_1/article/details/90524095