页面之间的跳转传参,正常前端js里写 window.location.href="xxxxx?id=1" 就可以了;
但是vue不一样 需要操作的是路由history,需要用到 VueRouter,
常用的场景是:列表页点击“查看”按钮,跳转到详情页。
在列表页(list.vue)按钮点击事件里写上
1 2 3 4 |
<span class="token function">detail</span><span class="token punctuation">(</span>row<span class="token punctuation">)</span> <span class="token punctuation">{</span> this<span class="token punctuation">.</span>$router<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token punctuation">{</span> path<span class="token punctuation">:</span> <span class="token string">"detail"</span><span class="token punctuation">,</span> query<span class="token punctuation">:</span> <span class="token punctuation">{</span> id<span class="token punctuation">:</span> row<span class="token punctuation">.</span>id <span class="token punctuation">}</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">,</span> |
运行时浏览器地址栏展示:
http://localhost:8080/#/orders/detail?id=31
在详情页(detail.vue)里写上
1 2 |
<span class="token keyword">let</span> id <span class="token operator">=</span> <span class="token function">Number</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>$route<span class="token punctuation">.</span>query<span class="token punctuation">.</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span> |
即可获取到参数id了。
先看看 route是什么,在vscode f12后
看到
1 2 3 4 5 6 7 |
<span class="token keyword">declare</span> module <span class="token double-quoted-string string">"vue/types/vue"</span> <span class="token punctuation">{</span> <span class="token keyword">interface</span> <span class="token class-name">Vue</span> <span class="token punctuation">{</span> <span class="token variable">$router</span><span class="token punctuation">:</span> VueRouter<span class="token punctuation">;</span> <span class="token variable">$route</span><span class="token punctuation">:</span> Route<span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> |
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。
VueRouter官网 传送门
route是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等
其中
from:https://www.jianshu.com/p/45163cb031be