【vue3】路由配置

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>

结果:

 

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值