小白都能看懂的vue中各种通信传值方式,附带详细代码

 

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(){        },   

                    
                
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信