简体   繁体   中英

How to open a new page on button click in vue 3?

I have this application with a button and I want to change to a different, Vue file. My first Vue file is called 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>

and then I have another file called 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>

So on the button click in-app.vue I want to go to gallery.vue. I am currently using Vue3 for this project.

You can always use Vue Router.

This tutorial will explain better than me :

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

essentially what you want to do is render different components

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

but that gets a bit unwieldly quite quickly ( though might be useful for something pretty simple. So quite often what people do is "client side" routing.

In Vue3, you can use the simple router in the docs https://v3.vuejs.org/guide/routing.html#simple-routing-from-scratch

or use something like VueRouter (which is pretty common)

<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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM