Javascript 强制在vue路由器哈希模式下使用window.location.href

Javascript 强制在vue路由器哈希模式下使用window.location.href,javascript,vue.js,vue-router,Javascript,Vue.js,Vue Router,我使用的是vue路由器3.0.1,模式是hash 当前url为: /#/?type=1 我尝试对相同的路径使用window.location.href,但使用了不同的查询参数,如下所示 window.location.href = '/#/?type=2'; 但是浏览器的url会发生变化,但不会发生其他任何事情 首先,我正在尝试这个,因为router.push没有重新渲染组件 原始的window.location.href应该给出不同的结果,但是vue路由器看起来要覆盖window.loca

我使用的是
vue路由器3.0.1
,模式是
hash

当前url为:

/#/?type=1
我尝试对相同的路径使用
window.location.href
,但使用了不同的查询参数,如下所示

window.location.href = '/#/?type=2';
但是浏览器的url会发生变化,但不会发生其他任何事情

首先,我正在尝试这个,因为
router.push
没有重新渲染组件

原始的
window.location.href
应该给出不同的结果,但是
vue路由器
看起来要覆盖
window.location.href


在这种情况下,我如何强制移动到
/#/?type=2

您不需要使用
window.location.href
来使其工作。这里的问题是,当您只更新查询参数时,组件会被重用,并且组件不会自动重新渲染。解决此问题的一种方法是观察组件中的$route。下面是一个代码示例。您还可以在这里找到JSFIDLE

Html

类型2
类型1
JavaScript
const Bar={
模板:“类型{{Type}}”,
数据(){
返回{
类型:“”
}
},
挂载(){
this.type=this.$route.query.type;
},
观察:{
$route(到、从){
//当管线更改时更新数据类型。
this.type=to.query.type;
}
} 
}
常量路由器=新的VueRouter({
模式:“哈希”,
路线:[
{路径:'',组件:Bar},
]
})
新Vue({
路由器,
el:“#应用程序”,
数据:{
味精:“你好,世界”
}
})

详细解释请参考官方文件

您不需要使用
window.location.href
使其工作。这里的问题是,当您只更新查询参数时,组件会被重用,并且组件不会自动重新渲染。解决此问题的一种方法是观察组件中的$route。下面是一个代码示例。您还可以在这里找到JSFIDLE

Html

类型2
类型1
JavaScript
const Bar={
模板:“类型{{Type}}”,
数据(){
返回{
类型:“”
}
},
挂载(){
this.type=this.$route.query.type;
},
观察:{
$route(到、从){
//当管线更改时更新数据类型。
this.type=to.query.type;
}
} 
}
常量路由器=新的VueRouter({
模式:“哈希”,
路线:[
{路径:'',组件:Bar},
]
})
新Vue({
路由器,
el:“#应用程序”,
数据:{
味精:“你好,世界”
}
})

详细解释请参考官方文件

不要强迫别人做任何事。更好的解决方案是更新组件。有很多方法不要强迫别人做任何事。更好的解决方案是更新组件。我说过我在使用散列模式,但我必须这样做。这没关系。将模式更改为“哈希”也可以。我已经更新了代码示例以反映这一点。如果您在本地服务器上运行一些vue路由器代码,您可以在url中看到
/#/?type=1
/#/?type=2
,如果您单击类型1或类型2链接或路由器推送的触发器,组件将得到更新。好的,我知道了。非常感谢。这是什么???我说我在使用散列模式,我必须这样做。这没关系。将模式更改为“哈希”也可以。我已经更新了代码示例以反映这一点。如果您在本地服务器上运行一些vue路由器代码,您可以在url中看到
/#/?type=1
/#/?type=2
,如果您单击类型1或类型2链接或路由器推送的触发器,组件将得到更新。好的,我知道了。非常感谢。这是什么???
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <!-- You can use router-link to trigger the url change or router.push in your code -- it doesn't matter. -->
  <router-link to="/?type=2">type 2</router-link>
  <router-link to="/?type=1">type 1</router-link>

  <router-view></router-view>
</div>

const Bar = { 
  template: '<div>Type {{type}}</div>',
  data () {
    return { 
      type: ''
    }
  },

  mounted () {
    this.type = this.$route.query.type;
  },

  watch: {
    $route(to, from) {
      // Update the data type when the route changes. 
      this.type = to.query.type;
    }
  } 
}

const router = new VueRouter({
  mode: 'hash',
  routes: [
    { path: '', component: Bar },

  ]
})

new Vue({
    router,
  el: '#app',
  data: {
    msg: 'Hello World'
  }
})