Quick navigation menu:
- vue project creation
- vue knowledge router routing (path parameters, query parameters, name the route, the route nested, named view, hash / history mode )
1, create a project vue step (windows environment). Before creating vue project, the system checks whether the conditions to create a project (whether already installed node.js, webpack, vue-cli)cmd to open the terminal.
1.1 If you have not installed node.js, then install node.js , after the installation is complete, view node version
node -v
1.2 Installation Taobao mirror, the installation is complete view npm version: npm -v
npm install -g cnpm --registry=https://registry.npm.taobao.org
1.3 Installation webpack
npm install webpack -g
1.4 Installation vue global scaffolding, vue-cli2.x use npm install -g cli-vue , vue-cli3.x use npm install -g @ vue / cli installation, see vue version: vue -V
npm install -g vue-cli
or
npm install -g @vue/cli
1.5 preparatory work done, officially created vue project , create vue project can choose between two ways. The following is my_vue_pro vue project name
vue init webpack my_vue_pro
or
view create my_vue_pro
vue init is initialized vue-cli2.x, you can use some templates github above to initialize the project, webpack is the official recommended standard template name. vue-cli2.x project to migrate 3.x should just copy the static directory to the public directory, src directory covering old project src directory 3.x of. vue create is initialized vue-cli3.x, the current template is fixed, freely configurable template option, to create out of the vue-cli3 project, with vue-cli2 different project structure, different configuration, the specific configuration reference official documents .
If vue version or 2.x, vue-cli2.x upgrade to the latest version from: unmount: npm Uninstall -g vue-cli , and then install the latest version of npm install -g @ vue / cli
1.6 cd into the project
cd my_vue_pro
1.7 add the required dependencies, such as adding routing vue vue-router dependencies may be used NPM the install vue-router , or vue add router
npm install vue-router
or
vue add router
1.8 install all dependencies, NPM the install . Uninstall dependencies: npm Uninstall xxx
cnpm install
1.9 Run the project, see how it works package.json file scripts script, npm RUN dev or npm run serve
npm run serve
2, vue vue-router routes illustrated
Vue Router is Vue.js official route manager. It Vue.js and core depth of integration, so that to build single-page application a breeze. Capabilities include:
- Nested routing / table view
- Modular, component-based routing configuration
- Routing parameters, queries, wildcard
- Based on the view transition effects Vue.js transition system
- Fine-grained control navigation
- CSS class with automatic activation link
- HTML5 historical patterns or hash mode, automatic demotion in IE9
- Since the definition of the scroll bar behavior
In order to deepen the understanding of the route, after installing vue-router package, if the project is automatically generated router.js, delete, we manually write a router.js. After creating router.js, then newly added two vue pages, naming pageA and pageB, as shown below:
Which router.js Code
import Vue from 'vue' import Router from 'vue-router' //自定义页面 import PageA from './views/PageA' import PageB from './views/PageB' //安装路由到vue Vue.use(Router) const routes = [ { path: '/', redirect: '/pageB' //重定向,设置默认进入pageB页面 }, { //动态路径参数,以冒号开头,如果有多个参数则继续往后面追加 path: '/pageA/:id/:name', name: 'pageA', component: PageA }, { path: '/pageB', name: 'pageB', component: PageB } ] export default new Router({ //mode: 'hash', //默认hash模式,hash模式有#;另外还有一种history模式,没有#符号 routes })
main.js是vue项目的入口脚本,在这里引入router.js, 传入路由配置。
import Vue from 'vue' import App from './App.vue' import router from './router.js' Vue.config.productionTip = false new Vue({ router, //key名字必须命名为router render: h => h(App) }).$mount('#app')
2.1 路由视图<router-view> 组件和 路由导航<router-link>组件
在项目启动模板页App.vue上面有个<router-view>路由视图组件,相当于是一个占位符一样(<slot>插槽也类似),之后页面的路由变化引起的页面替换都是在<router-view>路由视图上进行。
而<router-link>有点类似于超链接标签<a>,<router-link>上有个必写的属性to, 就类似于超链接<a>的href属性,设置要跳转的路由链接。
App.Vue测试代码:
<template> <div id="app"> <div id="nav"> <router-link to="/pageA/5188/王大锤">pageA</router-link> | <router-link to="/pageB">pageB</router-link> </div> <router-view/> </div> </template>
2.2 路径参数和查询参数
路径参数和查询参数作为页面之间的数据传递的一种方式,使用非常频繁。路径参数,望文生义意思是参数作为路径的一部分,在配置路由的时候把参数配置好,然后在浏览器中输入url时,必须传参,否则会找不到这个路由这个页面。例如,pageA页面的路由配置为:/pageA/:id/:name ,意思是pageA页面后面必须传一个id参数和name参数,这两个参数作为路径的一部分,必须传值。然后在pageA页面中用:this.$route.params 来获取所有的路径参数。
而查询参数则没有路径参数这么严格,路由不会对此做验证。路由参数在url中的表现为页面链接后面加 ?key=value&... , 然后在页面中用:this.$route.query 来获取所有查询参数。如下图:
我们打印this.$route变量,看到如上图右边部分内容:
- this.$route.name : 页面名字。这个name就是在router.js中配置的那个name, 这个name也是有大用处的,比如在<router-link>中使用“命名路由”的时候就是用到它,举例说明,通过在路由链接标签的to属性设置name和相应的参数,然后跳转效果和设置路由path是一样的:
<router-link :to="{ name: 'pageA', params: { id: 5188, name:'王大锤' }}">命名路由pageA</router-link>
- this.$route.path: 路由路径,包含路径参数,不包含查询参数
- this.$route.fullPath: 路由全路径,包含路径参数和查询参数
- this.$route.query: 路径所有查询参数
- this.$route.params: 路径所有路径参数
- this.$route.meta: 路由元信息,在配置路由的时候可以把自定义的一些数据存在meta中,用作其他用途
- this.$route.matched: 里面包含了路由的一些匹配信息
2.3 路由props设置及路径参数获取
在设置页面路由时,如果增加一个props属性,并设置为true, 则在页面中可以直接拿到参数,不需要通过this.$route.params来取参数。比如router.js中部分代码:
{ path: '/pageC/:id/:name', name: 'pageC', props: true, //设置props属性为true, 则可以在PageC页面中直接取参数 component: PageC }
在PageC页面中参数获取:
<template> <div class="box"> <h1>佛山 -- 黄飞鸿,from PageC </h1> <h3>男儿何不带吴钩,收取关山五十州</h3> <h3>路径参数id: {{this.id}}, name: {{this.name}}</h3> </div> </template> <script> export default { name: 'pageC', props: ['id', 'name'], //直接接收路径参数 created(){ console.log("id: ", this.id, ", name: ", this.name) } } </script>
2.4 嵌套路由。实际生活中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件。比如现在PageB页面中嵌入页面PageC, 则需要在PageB页面中增加一个路由视图<router-view>标签,作为嵌套页面PageC的占位符。
路由部分代码:
{ path: '/pageB', name: 'pageB', component: PageB, meta: { isOK: true, type: 9 }, children: [ { path: 'pageC/:id/:name', component: PageC, props: true, //设置props属性为true, 则可以在PageC页面中直接取参数 name: 'subPageC', meta: { requiresAuth: true, id: 51666 }, //自定义数据 } ] },
PageB页面中部分代码:
<template> <div class="box"> <h1>一片云 -- 罗小虎,from PageB </h1> <h3>千磨万击还坚劲,任尔东南西北风</h3> <!-- 嵌套路由,嵌套页面占位符 --> <router-view></router-view> </div> </template> <script> export default { name: 'pageB', created(){ console.log('...pageB...') console.log(this.$route) } } </script>
效果图:
2.5 编程式的导航。 <router-link>叫声明式导航,还有种编程式导航,格式为:router.push(location, onComplete?, onAbort?), 在页面中的使用例子:
// 字符串 router.push('home') // 对象 router.push({ path: 'home' }) // 命名的路由 router.push({ name: 'user', params: { userId: '123' }}) // 带查询参数,变成 /register?plan=private router.push({ path: 'register', query: { plan: 'private' }}) /*注意:如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。 取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path: */ const userId = '123' router.push({ name: 'user', params: { userId }}) // -> /user/123 router.push({ path: `/user/${userId}` }) // -> /user/123 // 这里的 params 不生效, 即编程式导航如果提供了path, 则路径参数必须写入path中。而查询参数可以不写入 router.push({ path: '/user', params: { userId }}) // -> /user
同样的编程式导航规则也适用于<router-link>导航组件的to属性
router.replace(location, onComplete?, onAbort?) 和router.push(...)很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。声明式导航替换用法: <router-link :to="..." replace> ,编程式导航替换用法: router.replace(...)
router.go(n)的使用,这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
。
// 在浏览器记录中前进一步,等同于 history.forward() router.go(1) // 后退一步记录,等同于 history.back() router.go(-1) // 前进 3 步记录 router.go(3) // 如果 history 记录不够用,那就默默地失败呗 router.go(-100) router.go(100)
2.6 命名视图。有时候想同时 (同级) 展示多个视图,而不是嵌套展示,例如创建一个布局,有 sidebar
(侧导航) 和 main
(主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view
没有设置名字,那么默认为 default
。
router.js中部分代码:
{ path: '/pageD', name: 'pageD', components: { //演示命名视图 default: PageD, tanA: PageA, tanB: PageB } }
App.vue中部分代码:
<router-view/> <!-- 命名视图, 路由视图名字匹配了,就会展示匹配的页面内容 --> <router-view name="tanA"/> <router-view name="tanB"/>
2.7 路由模式。默认路由模式是hash模式,即地址栏中域名后带有#符号(此 hash 不是密码学里的散列运算)。它的特点就是使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。不过看起来不是很美观,另外hash模式的路由,在作为回调地址和一些第三方公司合作时,会有点麻烦,比如如果想实现微信快捷登录或者获取微信用户授权时,当微信用户授权成功后,回跳回来时,微信返回的code参数会插入到#符号前面,这样的话就为了获取这个code,就需要一系列的另外操作了。
路由模式还有另外一种模式就是history模式,这种模式是没有#符号的,符合我们平常的使用习惯。这种模式充分利用 history.pushState
API 来完成 URL 跳转而无须重新加载页面。
export default new Router({ //mode: 'hash', //默认hash模式,hash模式有#;另外还有一种history模式,没有#符号 mode: 'history', //history模式,没有#符号 routes })
不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id
就会返回 404,这就不好看了。
所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html
页面,这个页面就是你 app 依赖的页面。