vue地址栏直接输入路由无效问题(回车也无效)

1、参考网址:https://www.jianshu.com/p/06b004c6772f

vue 项目只要不是静态页面,一般都会和官方的路由管理器 vue-router 一起使用。

最近项目有一个需求,是在地址栏输入路由,跳转到对应路由组件,在开发环境中这样做是可以跳转的,但是项目打包后,路由可以访问,但是回车会有404页面的报错

因为 vue 在页面上显示哪个组件是根据 vue-router 进行控制的,在地址栏上直接输入路由名称,并不能触发 vue-router 的规则,所以只能通过监听地址的改变,利用回调函数在组件内部进行动态修改路由。

方式:hashchange 事件

App.vue 中添加此事件:

mounted(){
    window.addEventListener('hashchange',()=>{
        var currentPath = window.location.hash.slice(1); // 获取输入的路由
        if(this.$router.path !== currentPath){
            this.$router.push(currentPath); // 动态跳转
        }
    },false);
}

需要在main.js中将// mode:"history" 注释掉

const router = new VueRouter({

routes : routes,

// mode:"history"

})

 

2、发布vue到正式环境不想要#但是可以正常回车得解决办法

参考网址:https://www.cnblogs.com/feigao/p/9103406.html

1.安装 url rewrite模块到IIS 

下载地址:https://www.iis.net/downloads/microsoft/url-rewrite

2.在web.config文件中 system.webServer 节点添加如下配置(如果没有,自行添加一个Web.config)

复制代码

  <system.webServer>
    <!--rewrite 节点,用于支持history模式-->
    <rewrite>
      <rules>
        <rule name="API Rule" stopProcessing="true">
          <match url="^(api|account|manage)(.*)$" />
          <action type="None" />
        </rule>
        <rule name="Angular Rule" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

版权声明:本文为zezeadede555原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。