main.js 引入router
时间: 2023-08-16 11:06:06 浏览: 41
在使用Vue.js开发单页应用时,我们通常会使用Vue Router来实现路由功能。具体引入router的步骤如下:
1. 在项目中安装Vue Router:可以使用npm或yarn进行安装。
2. 在main.js文件中引入Vue Router:
```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
// 配置路由
})
new Vue({
router,
render: h => h(App),
}).$mount('#app')
```
在上面的代码中,我们首先引入了Vue和Vue Router,并且通过Vue.use()方法将Vue Router安装到Vue中。然后,我们创建了一个路由实例,并将其传递给Vue实例的router选项中。最后,我们将Vue实例挂载到页面中。
3. 配置路由:在router实例中,我们需要配置路由规则。例如:
```javascript
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
]
})
```
在上面的代码中,我们配置了三个路由规则,分别对应三个组件:Home、About和Contact。当用户访问不同的URL时,将会显示不同的组件。
通过以上步骤,我们就成功的引入了Vue Router,并配置了路由规则。
相关推荐
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)