Vue中使用vue-router
- 1. 安装vue-router
- 2. 创建路由页面
- 3. 创建router文件
- 4. 挂载router
- 5. 使用
1. 安装vue-router
npm install vue-router@3.6.5 --save
2. 创建路由页面
HomeView.vue
<template><div>home</div>
</template><script>export default {name:'HmeView',data(){return{}},methods:{},created(){},mounted(){}}
</script><style lang=scss>
</style>
About.vue
<template><div>about</div>
</template><script>export default {name:'About',data(){return{}},methods:{},created(){},mounted(){}}
</script><style lang=scss>
</style>
3. 创建router文件
- 创建router文件夹,并创建index.js
//引入vue和vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入路由页面
import HomeView from '../views/HomeView.vue'
import VideoView from '../views/VideoView.vue'Vue.use(VueRouter)//定义路由
const routes = [{path:'/',name:'home',component: HomeView},{path:'/about',name:'about',component:()=>import(/*webpackChunkName:"about"*/'../views/About.vue')}
]
//创建路由
const router = new VueRouter({//模式mode:'history',//使用定义的路由routes
})export default router
4. 挂载router
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'Vue.config.productionTip = falsenew Vue({router,render: h => h(App),
}).$mount('#app')
5. 使用
App.vue
<template><div id='app'><!-- 使⽤router-link组件来导航 --><!-- 通过传⼊to属性指定连接 --><!-- router-link默认会被渲染成⼀个a标签 --><router-link to='home'>Home</router-link><router-link :to={name:'about'}>About</router-link><!-- 路由出⼝ 路由渲染位置 --><router-view/></div>
</template>