目录
0、vue3.0和vue2.0语法及注意事项(开始前必须了解)
个人理解:vue3.0是按需引用:onmethes、watch等;vue2.0是选项式,对号入座
详细讲解可以看:
基础> 想知道Vue3与Vue2的区别?五千字教程助你快速上手Vue3! - 简书 (jianshu.com)
注意:
> vue3.0中不要用this,setup中解析不到this,Vue3.0有语法糖的写法无需进行return
>在HTML中使用可以直接使用 <router-link to="/testA">testA</router-link>和@click="$router.push('/testA')";在JS代码块中需要进行引用 import { useRouter } from "vue-router";==>const router = useRouter();==>router.push('testB');
> ref 和 reactive,定义响应式数据使用;使用ref的时候在js中取值的时候需要加上.value,reactive更推荐去定义复杂的数据类型 ref 更推荐定义基本类型
1、引入路由
npm install vue-router
2、router参数及函数
详细:介绍 | Vue Router (vuejs.org)
3、简单实列
效果如下:
同理,网络上常见的后台管理系统左侧菜单也可以按此思路实现。
代码实现:
在src目录下创建pages文件夹,并创建testA.vue和testB.vue文件
src/pages/testA
<template>
<div>testA</div>
</template>
src/pages/testB
<template>
<div>testB</div>
</template>
src/App.vue
<template>
<router-view></router-view>
</template>
<script>
export default {
}
</script>
src/router/index.js
import { createRouter, createWebHashHistory } from "vue-router";
const globalRoutes=[
{
path: "/404",
name: "404",
component: () => import("@/pages/404.vue"),
},
];
const mainRoutes={
path: "/",
name: "AppMain",
component: () => import("@/pages/HelloWorld.vue"),
redirect: { name: "Home" },
children: [
{
path: "/home",
name: "Home",
component: () => import("@/pages/testA.vue"),
},
{
path: "/testA",
name: "testA",
component: () => import("@/pages/testA.vue"),
},
{
path: "/testB",
name: "testB",
component: () => import("@/pages/testB.vue"),
}
],
};
const router = createRouter({
history: createWebHashHistory(),//createWebHashHistory(),
scrollBehavior: () => ({ y: 0 }),
isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
routes: globalRoutes.concat(mainRoutes),
});
export default router;
src/main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'
const app=createApp(App);
app.use(router);
app.mount('#app');
开始在模板HelloWorld.vue中使用
<script setup>
import { useRouter } from "vue-router";
const router = useRouter();
function clickTestA(){
console.log('testa');
router.push('home');
};
const clickTestB=()=>{
console.log('/testb');
router.push('testB');
};
</script>
<template>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<button type="button" @click="clickTestA">testA</button>
<button type="button" @click="clickTestB">testB</button>
<button type="button" @click="$router.push('/testB')">testB</button>
<!-- <router-link to="/testA">testA</router-link>
<router-link to="/testB">testB</router-link> -->
<router-view></router-view>
</div>
</template>
4、复杂的实列:后台左侧菜单