我想在Vue.js中做一个类似于香草javascript的重定向

window.location.href = 'some_url'

我如何在Vue.js中实现这一点?


当前回答

在组件脚本标记中,您可以使用路由器并执行类似的操作

this.$router.push('/url-path')

其他回答

如果你正在使用vue-router,你应该使用router.go(path)来导航到任何特定的路由。路由器可以在组件中使用。$router来访问。

否则,window.location.href = 'some url';适用于非单页应用程序。

编辑:router.go()在VueJS 2.0中更改。你可以使用$router。Push ({name: "yourroutename"})或者只是router.push("yourroutename")现在重定向。

文档

注意:在控制器中使用:this.$router。Push ({name: 'routename'})

<div id="app">
   <a :href="path" />Link</a>
</div>

<script>
      new Vue({
        el: '#app',
        data: {
          path: 'https://www.google.com/'
        }
      });
</script> enter code here

只使用:

window.location.href = "http://siwei.me"

不要使用vue-router,否则会被重定向到 “http://yoursite.com/ # ! / http://siwei.me”

我的环境:节点6.2.1,vue 1.0.21, Ubuntu。

你也可以直接在模板上使用v-bind,就像…

<a :href="'/path-to-route/' + IdVariable">

:是v-bind的缩写。

为了与您最初的要求保持一致:

window.location.href = 'some_url'

你可以这样做:

<div @click="this.window.location='some_url'">
</div>

注意,这并没有利用Vue的路由器,但如果你想“在Vue.js中做一个类似于香草javascript的重定向”,这是可行的。