我如何使组件内的按钮更改vue路由器路径

时间:2019-10-14 18:46:17

标签: vue.js

我在组件内部有按钮。我正在为vuejs 2.5使用vue路由器,如果我单击此按钮,我想更改路径。每当我单击按钮时,如何使路径更新。

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<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">
  <router-link to="/">/home</router-link>
  <router-link to="/foo">/foo</router-link>
  <router-view></router-view>
  
  <script type="text/x-template" id="t1">
  <button>hello</button><br> 
  </script>
</div>
table {
  border: 1px solid;
  width: 400px;
  overflow: hidden;
}

tr:hover {
  background: gray;
}

tr td {
  border: 1px solid;
}

tr td:first-child {
  position:relative;
}

a:before {
  content: '';
  position:absolute;
  left: 0;
  top: 0;
  bottom: 0;
  display: block;
  width: 400px;
}

2 个答案:

答案 0 :(得分:0)

您可以使用vue-route https://router.vuejs.org/api/#to的“ to”道具

在标签道具上,您必须设置按钮值以渲染按钮 https://router.vuejs.org/api/#tag

<router-link
    to="/foo"
    tag="button">
        foo
</router-link>

答案 1 :(得分:0)

您可以简单地将点击监听器添加到按钮:

 <template>
  <div id="app">
    <button @click="redirectToHome()">Go Back</button>
    <button @click="redirectToFoo()">Click ME</button>
  </div>
</template>

并在方法中实现它们

<script>
export default {
  name: "#app",
  methods: {
    redirectToHome() {
      this.$router.push({ path: '/' });
    },
    redirectToFoo() {
      this.$router.push({ path: '/foo' });
    }
  }
};
</script>

有关程序化导航的更多详细信息: https://router.vuejs.org/guide/essentials/navigation.html#programmatic-navigation