vue-router的使用方法介绍

vue-router

对于大多数单页面应用,都推荐使用官方支持的 vue-router 库。

学习网址:https://router.vuejs.org/installation.html#direct-download-cdn

提示:本篇博客仅仅介绍搭建项目之后,再下载vue-router的情况,并非搭建项目是直接引入vue-router。

一、安装方法(npm方式)

在终端运行以下指令

npm install vue-router

注意:--save 与 --save-dev 的区别

--save(可以省略) 下载的第三方依赖到package.js中的dependencies。

--save-dev 下载开发时依赖,指环境配置,下载到package.js中的devDependencies,webpack、bable等等均属于开发

时依赖。

二、导入与使用

vue-router下载之后,需要在入口文件main.js导入,具体做法如下:

Vue.use(VueRouter);
Vue.use(VueAxios, axios);

// routes:数组,在该数组中配置所有的路由;
const routes = [
  {path:'/',component:myHome,name:'home'},
  {path:'/product/:productName/:price',component:myProduct,name:'product'}
];
// 创建router实例
const router = new VueRouter({
  routes
});
/* eslint-disable no-new */
new Vue({
  el: '#app',
  // 引入到根实例中才可以使用导航功能
  router,
  components: {App},
  template: '<App/>',
  data(){
    return {

    }
  }
})

三、官网介绍使用步骤

网址:https://router.vuejs.org/zh/guide/#javascript

// 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)

// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
  router
}).$mount('#app')

// 现在,应用已经启动了!


猜你喜欢

转载自blog.csdn.net/qq_41115965/article/details/80790195