【问题标题】:How to open a new page on button click in vue 3?如何在 vue 3 中单击按钮打开新页面?
【发布时间】:2021-01-13 14:11:07
【问题描述】:

我有一个带有按钮的应用程序,我想更改为不同的 Vue 文件。我的第一个 Vue 文件名为 app.vue。

<template>
  <div id="app">
    <button id="gettingStarted">Getting started</button>
  </div>
</template>

<script>

export default {
  name: 'App',
  components: {

  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
#gettingStarted {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  background:cornflowerblue;
  border-radius: 0.5rem;
  height: 2.5rem;
  width: 6%;
}
</style>

然后我有另一个名为 Gallery.vue 的文件

<template>
  <div id="app">
      <h4>25%</h4>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  components: {
    
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

所以在按钮上点击in-app.vue 我想去gallery.vue。我目前正在为这个项目使用 Vue3。

【问题讨论】:

  • 这是 SPA 的一部分吗?

标签: javascript vue.js


【解决方案1】:
<button id="gettingStarted" @click="click">Getting started</button>
...
import { useRouter } from 'vue-router'
export default {
    setup() {
        const router = useRouter()
        const click = () => {
            router.push({
                path: 'target path'
            })
        }
        return {
            click
        }
    }
}

【讨论】:

  • 它不工作,@click 不适合我。它在控制台中向我显示错误。但是如果我使用@submit.prevent 然后它不会显示错误但不会工作。
  • &lt;button type="button" id="gettingStarted" @click="click"&gt;Getting started&lt;/button&gt;
【解决方案2】:

基本上你想要做的是渲染不同的组件

<Component1 v-if="useComponent1" />
<Component2 v-if="useComponent2" />

但这很快就会变得有点笨拙(尽管可能对一些非常简单的事情有用。所以人们经常做的是“客户端”路由。

在 Vue3 中,您可以使用文档 https://v3.vuejs.org/guide/routing.html#simple-routing-from-scratch 中的简单路由器

或使用类似 VueRouter 的东西(这很常见)

【讨论】:

    【解决方案3】:

    您始终可以使用 Vue 路由器。

    本教程会比我解释得更好:

    https://appdividend.com/2018/12/28/vue-router-tutorial-with-example-how-to-use-routing-in-vuejs

    【讨论】:

    猜你喜欢
    • 2015-08-30
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多