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>
新聞熱點
疑難解答
圖片精選