今天就不先着急学习语法了,先搞了一下vue3.0的路由
Vue-Router
首先,我们npm一下
npm i vue-router@4
import {
createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: "/",
redirect: "/home"
},
{
path: "/home",
name: "home",
component: () => import('../components/HelloWorld.vue')
}, {
path: "/zjq",
component: () => import('../components/zjq.vue')
}
],
})
export default router
和vue2大同小异,都是创建路由实例对象,传递一个对象,设置模式,然后传入path数组,使用路由赖加载
component: () => import('../components/zjq.vue')
我们需要在main.js中引入,挂载
import {
createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router'
let A = createApp(App)
A.use(router)
A.mount('#app')
或者
链式写法
import {
createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router'
createApp(App).use(router).mount('#app')
这个时候还是不能直接写路由访问,需要在跟组件加上一行路由出口router-view
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
这个时候我们就可以使用路由了。
useRouter、useRoute
import {
useRouter, useRoute } from 'vue-router'
useRouter:在Vue2中可以直接this.$router得到我们路由实例的方法;
useRoute:在Vue2中可以直接this.$route得到我们路由实例的属性;
用法和Vue2的用法完全一致。
import {
useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
console.log(router,'router');
console.log(route,'route');
在第一个页面跳转到第二个页面
<template>
<div>
<button @click="goClick">跳转到第二个页面</button>
</div>
</template>
<script>
import axios from "../assets/js/index";
import {
useRouter, useRoute } from 'vue-router'
import {
ref, reactive,watch } from "vue";
export default {
name: "App",
setup() {
const router = useRouter()
const route = useRoute()
function goClick(params) {
router.push('/zjq')
}
console.log(route.params,'route.params')
return {
goClick};
}
};
</script>
第二个页面
<template >
<div class="container">
<button @click="backcc">返回到第一个页面</button>
</div>
</template>
<script>
import {
useRouter } from "vue-router";
import {
ref} from 'vue'
export default {
setup(){
let router = useRouter()
function backcc(params) {
router.push({
name:"home",
params:{
name:'zjq'
}
})
}
return {
backcc}
}
}
</script>
<style scoped>
</style>
当从第二个页面回到第一个页面后,我们可以看到打印出来了带来的params参数
console.log(route.params,'route.params')