vue-router 路由

官网

https://router.vuejs.org/zh/

千万注意,项目名称不能是 vue-router ,否则路由安装是会报错的;
报错信息如下:

npm ERR! code ENOSELF
npm ERR! Refusing to install package with name "vue-router" under a package
npm ERR! also called "vue-router". Did you name your project the same
npm ERR! as the dependency you're installing?
npm ERR!
npm ERR! For more information, see:
npm ERR!     <https://docs.npmjs.com/cli/install#limitations-of-npms-install-algorithm>

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2019-06-04T00_10_17_081Z-debug.log

# 翻译
npm犯错!代码ENOSELF
npm犯错!拒绝在软件包下安装名为“vue-router”的软件包
npm犯错!也称为“vue-router”。你给你的项目取了同样的名字吗
npm犯错!作为您正在安装的依赖项?
npm犯错!
npm犯错!有关更多信息,请参见:
npm犯错!< https://docs.npmjs.com/cli/install limitations-of-npms-install-algorithm > ? ?
npm犯错!完整的运行日志可在以下文件中找到:
npm犯错!? ? C:\Users\管理员\ AppData \漫游\ npm-cache \ _logs \ 2019 - 06 - 04 - t00_10_17_081z debug.log

这个错误出现的原因就是我们的项目名和路由插件重名了,所以创建的时候,项目名不要用 vue-router

步骤

  1. 创建项目
# 创建项目
vue create router-demo
# cd 到项目目录
cd router-demo
# 启动项目 
npm run serve
# less
npm i less-loader
npm i less -D
  1. 创建文件
src/router/index.js
  1. 安装路由
npm i vue-router
  1. vue-router 实际上是 vue的一个插件,所以要通过 Vue.use() 明确地安装路由功能:
【src/router/index.js】

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
【main.js】
import router from './router/index'
  1. 配置路由
【src/router/index.js】
import Vue from 'vue';
import VueRouter from 'vue-router';

// 导入组件
import Home from '../views/Home.vue';
import Login from '../views/Login.vue';
import News from '../views/News.vue';
import Not from '../views/Not.vue';

// 安装插件
Vue.use(VueRouter);

// new 一个路由对象,然后暴露出去,在 main.js页面将这个对象导入,放到 vue实例中;
export default new VueRouter({
    mode: 'history', // hash & history
    routes: [
        {
            path: '/',			// 路径
            component: Home		// 组件
        },
        {
            path: '/login.gx',
            component: Login
        },
        {
            path: '/news.gx',
            component: News
        },
        {
            path: '/404.gx',
            component: Not
        },
        // 404 放在最后; * 匹配任意路径
        // 路由是从上往下匹配,如果匹配到上边的路由就是用上边的,如果上边的全部匹配不到,就是用这一个,所以这个要放在最底下;
        {
            path: '*',
            // component: Not
            // 重定向 到 404页面
            redirect: '/404.gx'
        }
    ]
})
【main.js】

import router from './router/index'

new Vue({
  render: h => h(App),
  router
}).$mount('#app')
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/">Home</router-link>
<router-link to="/login.gx">Login</router-link>
<router-link to="/news.gx">News</router-link>

<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章