1、新建文件夹router

2、新建js文件

在router文件下新建routes.js及index.js

3、routes.js

在该js文件下添加路由

const routes = [
    {
        name: "test",
        path: "/test",
        component: () => import("../components/test.vue")
    }
]
export default routes;

其中,name和path为自定义,component后面import为vue的路径

4、index.js

在该js文件中添加:

import { createRouter, createWebHistory } from "vue-router"
import routes from "./routes"
var router=createRouter({
    history:createWebHistory(),
    routes
})
export default router

5、在main.js中配置路由js

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from "./router/index"

var app=createApp(App)
app.use(router)
app.mount('#app')

6、测试

①  App.vue文件中使用路由标签

② 新建跳转按钮(在自动生成的HelloWorld.vue)

<template>
  <h1>{{ msg }}</h1>
  <button @click="count++">count is: {{ count }}</button>
  <p>
    Edit <code>components/HelloWorld.vue</code> to test hot module replacement.
  </p>
  <button @click="toPage">跳转页面</button>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    toPage: function () {
      this.$router.push({
        name: "test",//name的值对应routes.js中的name值
        params: {
          name: "张三", //传递参数
        },
      });
    },
  },
};
</script>

③新建vue文件

<!--  -->
<template>
  <div>我路由过来的名字:{{ name }}</div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
    };
  },
  created() {
    this.getName();
  },
  methods: {
    getName: function () {
      this.name = this.$route.params.name;//获取路由参数
    },
  },
};
</script>
<style  scoped>
</style>

结果:

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐