在 vue-router 中静默更新 url 而不触发路由 [英] Silently update url without triggering route in vue-router

查看:83
本文介绍了在 vue-router 中静默更新 url 而不触发路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新 url 的哈希值,而不实际触发 vue-router 去那个路由.诸如此类的东西:

I need to update the hash of the url, without actually triggering the vue-router to go to that route. Something in the likes of:

router.replace('my/new/path', {silent:true})

这会将 url 更新为 .../#/my/new/path,但路由器本身不会路由到该路径.

This would update the url to .../#/my/new/path, but the router itself would not route to that path.

有没有一种优雅的方法来实现这一目标?

Is there an elegant way to achieve this?

推荐答案

Vue 路由器要么打开要么关闭,所以你不能让它不检测某些 url".也就是说,如果 Vue 不需要销毁组件并允许您为 url 设置别名,它确实会重用组件.这允许您将 iframe 应用程序中的 url 作为路由中的别名,并在此期间保持相同的组件处于活动状态,防止您的 iframe 重新加载.

The Vue router is either on or off, so you cannot "make it not detect certain urls". That said, Vue does re-use components if it doesn't need to destroy them and allows you to alias urls. This allows you to have the urls from your iframe application as aliases in your route, and keep the same component alive during that time, preventing your iframe from getting reloaded.

// router.js
import Comp1 from "./components/Comp1";
import Comp2 from "./components/Comp2";

export default [
  {
    path: "/route1",
    component: Comp1,
    alias: ["/route2", "/route3", "/route4"]
  },
  {
    path: "/otherroute",
    component: Comp2
  }
];

// main.js
import Vue from "vue";
import App from "./App";
import VueRouter from "vue-router";
import routes from "./router";

Vue.config.productionTip = false;
Vue.use(VueRouter);

const router = new VueRouter({
  routes
});

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: { App },
  template: "<App/>"
});

在本例中,route1route2route3route4 都将被视为 route1 必须被加载,导致你的组件 Comp1 保持活动状态.

In this example, route1, route2, route3 and route4 will all be treated as if route1 has to be loaded, causing your component Comp1 to stay alive.

这篇关于在 vue-router 中静默更新 url 而不触发路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆