vue3.0 use vue-router

Download
vue3.0
yarn global add @vue/cli@next
or
npm install -g @vue/cli@next
The next step is to build scaffolding
Vue3.0 uses vite
Vite is a web development and build tool that allows code to be provided quickly due to its native ES module import method.

npm init vite-app your project name
cd vite-app
npm install

Here we can run the program, but we still need to use vue-router, so we need to download vue-router

npm install [email protected] --save

I am using Gaode here, the latest vue-router4.0
After the download is complete, we will start the program

npm run dev

Then we create a router.js file for editing

import {
    
     createRouter,createWebHistory } from 'vue-router'
import index from './components/index.vue'
import login from './components/login.vue'
const routerHistory = createWebHistory()
const routes = [
    {
    
    
        path:'/',
        name:'index',
        component:index
    }, 
    {
    
    
        path:'/login',
        name:'login',
        component:login
    }
]
const router = createRouter({
    
    
    history: routerHistory,
    routes
})
export default router

In the above code, we first import vue-router and then create routes in the same way as in vue2.0, and
finally export router

Then
we go to main.js

To introduce the router.js created by yourself
and then mount the router to the app

import {
    
     createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './index.css'
const app = createApp(App);
app.use(router);
app.mount('#app');

This way we can use routing

<template>
  <div @click="gotopath('/login')">点我去登录</div>
  <div @click="gotopath('/')">点我去首页</div>
  <router-view></router-view>
</template>

<script>
export default {
    
    
  name: 'HelloWorld',
  props: {
    
    
    msg: String
  },
  data() {
    
    
    return {
    
    
      count: 0
    }
  },
  methods:{
    
    
    gotopath(e){
    
    
      this.$router.push(e)
    }
  }
}
</script>

insert image description here
Don't forget to create the corresponding file yourself before using

Guess you like

Origin blog.csdn.net/weixin_44655037/article/details/112985003