最近使用了vue3中的路由器,记录一下。
1.首先安装路由,我使用的是pnpm,也可以使用npm安装

pnpm i vue-router@4
或者
npm i vue-router@4

2.新建页面a.vue

<script setup>
 import { ref } from "vue";
</script>

<template>
a
</template>

<style scoped>
</style>

3.在页面创建router文件夹,新建页面在这里插入图片描述
index.js

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

router.js

const routes = [
{
        name: 'h',
        path: '/',
        component: () => import('../components/HelloWorld.vue')
    },
    {
        name: 'a',
        path: '/a',
        component: () => import('../components/a.vue')
    }
    
];
 
export default routes//导出

在main.js配置

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index.js'
import ElementUI from 'element-plus'
import 'element-plus/dist/index.css'
createApp(App).use(router).use(ElementUI).mount('#app')

下面就可以跳转页面了,由于vue3和vue2跳转方式不一样,所以我一开始还是使用this.$router.push来跳转,结果报错,然后在网上看才发现也是按需引入,然后才能使用。
跳转路由界面 h.vue

<script setup>
import { onMounted, ref } from "vue";
//引入路由
import { useRouter } from "vue-router";
function zoomImg(obj) {
  console.log(obj.$el, "obj");
  // 一开始默认是100%
  let zoom = parseInt(obj.$el.style.zoom, 10) || 100;
  // 滚轮滚一下wheelDelta的值增加或减少120
  zoom += event.wheelDelta / 12;
  if (zoom > 0) {
    obj.$el.style.zoom = zoom + "%";
  }
  return false;
}
let fontbig = ref('大号字');
    var app = document.getElementById("app");
function bigfontsize() {
  if (fontbig.value=='大号字') {
    fontbig.value='普通字号'
    app.style.fontSize=30+'px'
    console.log(fontbig.value,'进入');
  } else {
    fontbig.value='大号字'
    app.style.fontSize=20+'px'
    console.log(fontbig.value,'不进入');
  }
}
//创建route
 const route = useRouter();
function com() {
//跳转页面
  route.push({path:'/a'})
}
onMounted(() => {
  
});

</script>

<template>
<p>文字</p>
  <el-button type="primary" @click="bigfontsize" v-html="fontbig"></el-button>
  <div
    style="width: 100px; height: 100px; background-color: red"
    @mousewheel="zoomImg(this)"
  >
    <img src="../assets/logo.png" @mousewheel="zoomImg(this)" />
  <el-button type="primary" @click="com">进入</el-button>

  </div>
</template>

<style scoped>
</style>

App.vue

<script setup>
</script>

<template>
  <router-view></router-view>
</template>

<style>
</style>

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐