createWebHistory路由模式路径不带#号(生产环境下不能直接访问项目,需要nginx转发) createWebHashHistory路由模式路径带#号
/* router/index.js */
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home,
beforeEach (to, from, next) {
// 单独给某个组件加守卫也是没变
},
afterEach (to, from, next) {
//
}
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = createRouter({
history: createWebHashHistory(), // 这要改模式的话在上面引入createWebHistory,这也用它
routes
})
// 可以动态添加路由
const home = () => import('../views/Home.vue')
const obj = { name: 'test', path: '/test', component: home }
router.addRoute(obj)
// 这的路由守卫还是和vue2.x 一样的
router.beforeEach((to, from, next) => {
next()
})
export default router
在home.vue中使用路由
<script>
// 但是这个就没有包括beforeRouteLeave了
import { useRouter, useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
import { ref } from 'vue'
export default {
name: 'Home',
setup () {
const router = useRouter() // 相当于this.$router
const route = useRoute() // 相当于this.$route
const num = ref(0)
onBeforeRouteUpdate((to, from) => { // 当前组件路由改变后,进行触发
console.log('update')
})
onBeforeRouteLeave((to, from) => { // 离开当前的组件,触发
console.log('leave')
})
return {
num
}
},
beforeRouteEnter (to, from, next) {
// ...因为兼容2.x所以这些也是可以用的,不过跟setup中的会有重复
},
beforeRouteLeave (to, from, next) {
// ...
}
}
</script>
除此之外:
// 使用方法传递参数这些都与2.x一样
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<router-view/>
|