最近vuejs项目结束了,下面就总结下如何在组件(页面)之间互相传值~
设置localstorage:
window.localStorage.setItem(name, content);
设置cookies:
Cookies.set(name, content);
设置localstorage:
window.localStorage.setItem(name, content);
设置cookies:
Cookies.get(name);
可以调取层级间的关系:
this.$parent.$data.id //获取父元素中的id
this.$children.$data.id //获取子元素中的id
这样操作会造成代码的耦合性太强,不利于后期维护
父页面代码:
this.$router.push({ name: 'routePage', query/params: { routeParams: params } })
子页面获取传值:
this.$route.params.paramName this.$route.query.paramName
params传值的话,在url里是看不到传值的,刷新页面后,数据会丢失;
query传值则不会出现刷新页面丢失问题,但是会造成url过长。
这两个方法共有缺点是,如果不是通过路由过来的请求,页面会无法正常访问。
注:在使用params时,也可以做到刷新页面,参数不丢失
{ path: '/OrderDetail/:orderId/:type', name: 'OrderDetail', component: OrderDetail, meta: { title: '订单详情', needAuth: true } }
使用时:
this.$router.push({name: 'OrderDetail', params: {orderId: id, type: 'buy'}})
参考我的这篇文章:
Vue.js如何解决组件之间的传值问题,子组件和父组件之间的相互传值
以上四种方法都可以实现vue.js页面(组件)之间的互相传值。