vue 通信、传值的多种方式(超详细)
前些天發(fā)現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
一、通過路由帶參數進行傳值
①兩個組件 A和B,A組件通過query把orderId傳遞給B組件(觸發(fā)事件可以是點擊事件、鉤子函數等)
②在B組件中獲取A組件傳遞過來的參數
this.$route.query.orderId二、通過設置 Session Storage緩存的形式進行傳遞
①兩個組件A和B,在A組件中設置緩存orderData
②B組件就可以獲取在A中設置的緩存了
const dataB = JSON.parse(sessionStorage.getItem('緩存名稱'))此時 dataB 就是數據 orderData
朋友們可以百度下 Session Storage(程序退出銷毀) 和 Local Storage(長期保存) 的區(qū)別。
三、父子組件之間的傳值
(一)父組件往子組件傳值props
①定義父組件,父組件傳遞 number這個數值給子組件,如果傳遞的參數很多,推薦使用json數組{}的形式
②定義子組件,子組件通過 props方法獲取父組件傳遞過來的值。props中可以定義能接收的數據類型,如果不符合會報錯。
當然也可以簡單一點,如果不考慮數據類型,直接 props:["number","string"]就可以了,中括號包裹,多個值使用,分隔。
③假如接收的參數 是動態(tài)的,比如 input輸入的內容 v-model的形式
注意:傳遞的參數名稱 支持駝峰命名,下圖 描述不正確(1.0是不支持的)
④父子組件傳值,數據是異步請求,有可能數據渲染時報錯
原因:異步請求時,數據還沒有獲取到但是此時已經渲染節(jié)點了
解決方案:可以在 父組件需要傳遞數據的節(jié)點加上 ?v-if = false,異步請求獲取數據后,v-if = true
(二)、子組件往父組件傳值,通過emit事件
四、不同組件之間傳值,通過eventBus(小項目少頁面用eventBus,大項目多頁面使用 vuex)
①定義一個新的vue實例專門用于傳遞數據,并導出
②定義傳遞的方法名和傳輸內容,點擊事件或鉤子函數觸發(fā)eventBus.emit事件
③接收傳遞過來的數據
注意:enentBus是一個另一個新的Vue實例,區(qū)分兩個this所代表得vue實例
五、vuex進行傳值
為什么使用vuex?
vuex主要是是做數據交互,父子組件傳值可以很容易辦到,但是兄弟組件間傳值(兄弟組件下又有父子組件),或者大型spa單頁面框架項目,頁面多并且一層嵌套一層的傳值,異常麻煩,用vuex來維護共有的狀態(tài)或數據會顯得得心應手。
需求:兩個組件A和B,vuex維護的公共數據是 餐館的名稱 resturantName,默認餐館名稱是 飛歌餐館,那么現在A和B頁面顯示的就是飛歌餐館。如果A修改餐館名稱 為 A餐館,則B頁面顯示的將會是 A餐館,反之B修改同理。這就是vuex維護公共狀態(tài)或數據的魅力,在一個地方修改了數據,在這個項目的其他頁面都會變成這個數據。
?????????? ? ? ?
①使用 vue-cli腳手架工具創(chuàng)建一個工程項目,工程目錄,創(chuàng)建組件A和組件B路由如下:
路由如下:
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的意思是 導入這個文件里面的所有內容,就不用一個個實例來導入了。
③actions
// 給action注冊事件處理函數。當這個函數被觸發(fā)時候,將狀態(tài)提交到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狀態(tài)的唯一合法方法 export const modifyAName = (state, name) => { // A組件點擊更改餐館名稱為 A餐館state.resturantName = name // 把方法傳遞過來的參數,賦值給state中的resturantName } export const modifyBName = (state, name) => { // B組件點擊更改餐館名稱為 B餐館state.resturantName = name }⑤getters
// 獲取最終的狀態(tài)信息 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']) // 動態(tài)計算屬性,相當于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']) // 動態(tài)計算屬性,相當于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?
?
總結
以上是生活随笔為你收集整理的vue 通信、传值的多种方式(超详细)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STM32工程建立
- 下一篇: 解决:[ERROR] Error exe