vue构建单页面应用实战(3)

module.exports = { 'https://www.jb51.net/': { component: require('./components/index') }, '/list': { component: require('./components/list') }, //增加详情页的跳转路由,并在路径上加上id传参,具名为name:show '/show/:id': { name:"show", component: require('./components/show') }, '*': { component: require('./components/notFound') } }

添加组件 show

components/show.js

module.exports = { template: require('../templates/show.html'), data:function(){ return {}; }, created:function(){ //获取params的参数ID var id=this.$route.params.id; //根据获取的参数ID,返回不同的data对象(真实业务中,这里应该是Ajax获取数据) if (id==1){ this.$data={"id":id,"name":"hello111","age":24}; }else{ this.$data={"id":id,"name":"hello222","age":28}; } }, ready: function () { console.log(this.$data); } };

templates/show.html

<h1>Show</h1> <hr/> <p>Hello show page!</p> <p>id:${id}</p> <p>name:${name}</p> <p>age:${age}</p>

修改 templates/item.html

复制代码 代码如下:


<p>我是subitem: <a v-link="{name:'show',params: { 'id': id } }"> ${id} : ${name}</a> </p>

这里 name:‘show' 表示具名路由路径,params 就是传参。

继续浏览器里点到详情页试试:

vue构建单页面应用实战

点击“hello11”,跳转到详情页:

vue构建单页面应用实战

传参逻辑成功。

12. 嵌套路由

仅有路由跳转是远远不够的,很多情况下,我们还有同一个页面上,多标签页的切换,在 vue 中,用嵌套路由,也可以非常方便的实现。

添加两个小组件

components/tab1.js

module.exports = { template: "<p>Tab1 content</p>" };

components/tab2.js

module.exports = { template: "<p>Tab2 content</p>" };

修改 components/index.js 组件,挂载这两个子组件

import tab1 from "./tab1"; import tab2 from "./tab2"; module.exports = { template: require('../templates/index.html'), components:{ "tab1":tab1, "tab2":tab2 }, ready: function () { } };

在路由里加上子路由

module.exports = { 'https://www.jb51.net/': { component: require('./components/index'), //子路由 subRoutes:{ "/tab1":{ component:require('./components/tab1') }, "/tab2":{ component:require('./components/tab2') } } }, '/list': { component: require('./components/list') }, '/show/:id': { name:"show", component: require('./components/show') }, '*': { component: require('./components/notFound') } }

好了,在浏览器里试一下:

初始状态:

vue构建单页面应用实战

点了 tab1,tab2:

vue构建单页面应用实战

 

Tab 切换没问题,可是,初始状态显示是空的,能不能默认显示 Tab1 Content 呢?很简单,调整下路由就可以了:

module.exports = { 'https://www.jb51.net/': { component: require('./components/index'), //子路由 subRoutes:{ //默认显示Tab1 "https://www.jb51.net/":{ component:require('./components/tab1') }, "/tab1":{ component:require('./components/tab1') }, "/tab2":{ component:require('./components/tab2') } } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwyyjd.html