Vue通信、傳值的多種方式,詳解(都是干貨):
一、通過路由帶參數進行傳值
①兩個組件 A和B,A組件通過query把orderId傳遞給B組件(觸發事件可以是點擊事件、鈎子函數等)
this.$router.push({ path: '/conponentsB', query: { orderId: 123 } }) // 跳轉到B
②在B組件中獲取A組件傳遞過來的參數
this.$route.query.orderId
二、通過設置 Session Storage緩存的形式進行傳遞
①兩個組件A和B,在A組件中設置緩存orderData
const orderData = { 'orderId': 123, 'price': 88 } sessionStorage.setItem('緩存名稱', JSON.stringify(orderData))
②B組件就可以獲取在A中設置的緩存了
const dataB = JSON.parse(sessionStorage.getItem('緩存名稱'))
此時 dataB 就是數據 orderData
朋友們可以百度下 Session Storage(程序退出銷毀) 和 Local Storage(長期保存) 的區別。
三、父子組件之間的傳值
(一)父組件往子組件傳值props
①定義父組件,父組件傳遞 number這個數值給子組件,如果傳遞的參數很多,推薦使用json數組{}的形式
②定義子組件,子組件通過 props方法獲取父組件傳遞過來的值。props中可以定義能接收的數據類型,如果不符合會報錯。
當然也可以簡單一點,如果不考慮數據類型,直接 props:["number","string"]就可以了,中括號包裹,多個值使用,分隔。
注:props:{
}
③假如接收的參數 是動態的,比如 input輸入的內容 v-model的形式
注意:傳遞的參數名稱 支持駝峰命名,下圖 描述不正確(1.0是不支持的)
④父子組件傳值,數據是異步請求,有可能數據渲染時報錯
原因:異步請求時,數據還沒有獲取到但是此時已經渲染節點了
解決方案:可以在 父組件需要傳遞數據的節點加上 v-if = false,異步請求獲取數據后,v-if = true
(二)、子組件往父組件傳值,通過emit事件
四、不同組件之間傳值,通過eventBus(小項目少頁面用eventBus,大項目多頁面使用 vuex)
①定義一個新的vue實例專門用於傳遞數據,並導出

②定義傳遞的方法名和傳輸內容,點擊事件或鈎子函數觸發eventBus.emit事件
③接收傳遞過來的數據
注意:enentBus是一個另一個新的Vue實例,區分兩個this所代表得vue實例
五、vuex進行傳值
為什么使用vuex?
vuex主要是是做數據交互,父子組件傳值可以很容易辦到,但是兄弟組件間傳值(兄弟組件下又有父子組件),或者大型spa單頁面框架項目,頁面多並且一層嵌套一層的傳值,異常麻煩,用vuex來維護共有的狀態或數據會顯得得心應手。
需求:兩個組件A和B,vuex維護的公共數據是 餐館的名稱 resturantName,默認餐館名稱是 飛歌餐館,那么現在A和B頁面顯示的就是飛歌餐館。如果A修改餐館名稱 為 A餐館,則B頁面顯示的將會是 A餐館,反之B修改同理。這就是vuex維護公共狀態或數據的魅力,在一個地方修改了數據,在這個項目的其他頁面都會變成這個數據。
①使用 vue-cli腳手架工具創建一個工程項目,工程目錄,創建組件A和組件B路由如下:
import Vue from 'vue' import Router from 'vue-router' import componentsA from '@/components/componentsA' import componentsB from '@/components/componentsB' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', name: 'componentsA', component: componentsA }, { path: '/componentsA', name: 'componentsA', component: componentsA }, { path: '/componentsB', name: 'componentsB', component: componentsB } ] })
app.vue
<template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
②開始使用vuex,新建一個 sotre文件夾,分開維護 actions mutations getters
②在store/index.js文件中新建vuex 的store實例
*as的意思是 導入這個文件里面的所有內容,就不用一個個實例來導入了。
import Vue from 'vue' import Vuex from 'vuex' import * as getters from './getters' // 導入響應的模塊,*相當於引入了這個組件下所有導出的事例 import * as actions from './actions' import * as mutations from './mutations' Vue.use(Vuex) // 首先聲明一個需要全局維護的狀態 state,比如 我這里舉例的resturantName const state = { resturantName: '飛歌餐館' // 默認值 // id: xxx 如果還有全局狀態也可以在這里添加 // name:xxx } // 注冊上面引入的各大模塊 const store = new Vuex.Store({ state, // 共同維護的一個狀態,state里面可以是很多個全局狀態 getters, // 獲取數據並渲染 actions, // 數據的異步操作 mutations // 處理數據的唯一途徑,state的改變或賦值只能在這里 }) export default store // 導出store並在 main.js中引用注冊。
③actions
// 給action注冊事件處理函數。當這個函數被觸發時候,將狀態提交到mutations中處理 export function modifyAName({commit}, name) { // commit 提交;name即為點擊后傳遞過來的參數,此時是 'A餐館' return commit ('modifyAName', name) } export function modifyBName({commit}, name) { return commit ('modifyBName', name) } // ES6精簡寫法 // export const modifyAName = ({commit},name) => commit('modifyAName', name)
④mutations
// 提交 mutations是更改Vuex狀態的唯一合法方法 export const modifyAName = (state, name) => { // A組件點擊更改餐館名稱為 A餐館 state.resturantName = name // 把方法傳遞過來的參數,賦值給state中的resturantName } export const modifyBName = (state, name) => { // B組件點擊更改餐館名稱為 B餐館 state.resturantName = name }
⑤getters
// 獲取最終的狀態信息 export const resturantName = state => state.resturantName
⑥在main.js中導入 store實例
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, // 這樣就能全局使用vuex了 components: { App }, template: '<App/>' })
④在組件A中,定義點擊事件,點擊 修改 餐館的名稱,並把餐館的名稱在事件中用參數進行傳遞。
...mapactions 和 ...mapgetters都是vuex提供的語法糖,在底層已經封裝好了,拿來就能用,簡化了很多操作。
其中...mapActions(['clickAFn']) 相當於this.$store.dispatch('clickAFn',{參數}),mapActions中只需要指定方法名即可,參數省略。
...mapGetters(['resturantName'])相當於this.$store.getters.resturantName
<template> <div class="componentsA"> <P class="title">組件A</P> <P class="titleName">餐館名稱:{{resturantName}}</P> <div> <!-- 點擊修改 為 A 餐館 --> <button class="btn" @click="modifyAName('A餐館')">修改為A餐館</button> </div> <div class="marTop"> <button class="btn" @click="trunToB">跳轉到B頁面</button> </div> </div> </template> <script> import {mapActions, mapGetters} from 'vuex' export default { name: 'A', data () { return { } }, methods:{ ...mapActions( // 語法糖 ['modifyAName'] // 相當於this.$store.dispatch('modifyName'),提交這個方法 ), trunToB () { this.$router.push({path: '/componentsB'}) // 路由跳轉到B } }, computed: { ...mapGetters(['resturantName']) // 動態計算屬性,相當於this.$store.getters.resturantName } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .title,.titleName{ color: blue; font-size: 20px; } .btn{ width: 160px; height: 40px; background-color: blue; border: none; outline: none; color: #ffffff; border-radius: 4px; } .marTop{ margin-top: 20px; } </style>
B組件同理
<template> <div class="componentsB"> <P class="title">組件B</P> <P class="titleName">餐館名稱:{{resturantName}}</P> <div> <!-- 點擊修改 為 B 餐館 --> <button class="btn" @click="modifyBName('B餐館')">修改為B餐館</button> </div> <div class="marTop"> <button class="btn" @click="trunToA">跳轉到A頁面</button> </div> </div> </template> <script> import {mapActions, mapGetters} from 'vuex' export default { name: 'B', data () { return { } }, methods:{ ...mapActions( // 語法糖 ['modifyBName'] // 相當於this.$store.dispatch('modifyName'),提交這個方法 ), trunToA () { this.$router.push({path: '/componentsA'}) // 路由跳轉到A } }, computed: { ...mapGetters(['resturantName']) // 動態計算屬性,相當於this.$store.getters.resturantName } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .title,.titleName{ color: red; font-size: 20px; } .btn{ width: 160px; height: 40px; background-color: red; border: none; outline: none; color: #ffffff; border-radius: 4px; } .marTop{ margin-top: 20px; } </style>
來源:https://blog.csdn.net/qq_35430000/article/details/79291287
增加:
父組件獲取子組件數據
父組件通過$refs獲取子組件的數據和方法
1.可獲取類型
- 子組件屬性
- 子組件方法
2.操作步驟
1.調用子組件的時候調用一個ref
<v-fgsheader ref="header"></v-fgsheader>
2.在父組件中通過
this.$refs.header.屬性
this.$refs.header.方法
3.適用場景
子組件給父組件傳值
4.示例代碼
父組件
<template> <div class="FGSHome"> <v-fgsheader ref="header"></v-fgsheader> <button @click="getChildProp()">獲取子組件的屬性的值</button> <button @click="getChildMethod()">獲取子組件的方法</button> </div> </template> <script> import FGSHeader from './FGSHeader.vue' export default{ data(){ return { } }, components:{ 'v-fgsheader':FGSHeader, }, methods: { getChildProp(){ alert(this.$refs.header.msg); }, getChildMethod(){ this.$refs.header.run(); } }, } </script>
子組件
<script> export default{ data(){ return { msg:"我是子組件header的值喲" } }, methods:{ run(){ alert("這是子組件Header的方法+"+this.msg); } } } </script>
子組件獲取父組件數據
子組件通過$parent獲取父組件的數據和方法,這種傳值方式實際上類似於上邊的屬性傳值中父組件給子組件的傳遞了子類對象this
,只不過Vue官方給封裝好了。
1.可獲取類型
- 父組件屬性
- 父組件方法
2.操作步驟
直接在子組件中使用this.$parent.XX
,不需要做任何多余操作。
3.適用場景
父組件給子組件傳值
4.示例代碼
子組件
getFatherProp(){ alert(this.$parent.fatherMsg); }, getFatherMethod(){ this.$parent.fatherRun(); }