1、路由通信传值
路由通信是通过路由跳转用query把参数带过去,也是vue常用的通信手段。
例子:创建并在路由注册一个组件Head
<template> <div id="head"> <button @click="handleChange">clickMe</button> //给按钮绑定点击事件 </div> </template><script>export default { name: 'Head', data () { return { } }, mounted(){ }, updated(){ }, methods:{ handleChange(){ this.$router.push({ path:"/about" , query:{ text:"我是阿格斯之盾" } }) //路由跳转,并用query带过去参数 } }}</script><style scoped></style>
创建另一个组件About并在路由注册
<template> <div id="about"> <p>我是关于页:{{ message }}</p><button type="button" @click="handleChange">回到首页</button> //显示接收过来的数据 </div> </template><script>export default { name: 'About', data () { return { message: "" } }, mounted(){ this.message = this.$route.query.text //在生命周期中接收传过来的数据 }, updated(){ }, methods:{ handleChange(){ this.$router.push({ path: "/" }) //点击返回首页 } }}</script><style scoped></style>
路由注册的简单代码
import Vue from 'vue'import Router from 'vue-router'import Head from '@/components/Head'import About from '@/components/About'Vue.use(Router)export default new Router({ mode: "history", routes: [ { path: '/', name: 'Head', component: Head },{ path: '/about', name: 'About', component: About } ]})
2、sessionStorage本地缓存通信
还是列举上面的例子,将它们稍微改一改就可以了,路由配置都一样的。sessionStorage的特点就是浏览器关掉缓存就会消失,这是它区别于localStorage的。
例子: Heade代码:
<template> <div id="head"> <button @click="handleChange">clickMe</button> </div> </template><script>export default { name: 'Head', data () { return { } }, updated(){ }, methods:{ handleChange(){ this.$router.push({ path:"/about"}) }, message(){ var message = "我是阿格斯之盾" sessionStorage.setItem('text', message) //创建缓存 } }, mounted(){ this.message(); }}</script><style scoped></style>
About代码:
<template> <div id="about"> <p>我是关于页:{{ message }}</p><button type="button" @click="handleChange">回到首页</button> </div> </template><script>export default { name: 'About', data () { return { message: "" } }, mounted(){ this.message = sessionStorage.getItem("text") //读取缓存 }, updated(){ }, methods:{ handleChange(){ this.$router.push({ path: "/" }) } }}</script><style scoped></style>
新闻热点
疑难解答
图片精选