vue 通信、传值的多种方式(超详细)
前些天發(fā)現(xiàn)了一個(gè)巨牛的人工智能學(xué)習(xí)網(wǎng)站,通俗易懂,風(fēng)趣幽默,忍不住分享一下給大家。點(diǎn)擊跳轉(zhuǎn)到教程。
一、通過(guò)路由帶參數(shù)進(jìn)行傳值
①兩個(gè)組件 A和B,A組件通過(guò)query把orderId傳遞給B組件(觸發(fā)事件可以是點(diǎn)擊事件、鉤子函數(shù)等)
②在B組件中獲取A組件傳遞過(guò)來(lái)的參數(shù)
this.$route.query.orderId二、通過(guò)設(shè)置 Session Storage緩存的形式進(jìn)行傳遞
①兩個(gè)組件A和B,在A組件中設(shè)置緩存orderData
②B組件就可以獲取在A中設(shè)置的緩存了
const dataB = JSON.parse(sessionStorage.getItem('緩存名稱'))此時(shí) dataB 就是數(shù)據(jù) orderData
朋友們可以百度下 Session Storage(程序退出銷毀) 和 Local Storage(長(zhǎng)期保存) 的區(qū)別。
三、父子組件之間的傳值
(一)父組件往子組件傳值props
①定義父組件,父組件傳遞 number這個(gè)數(shù)值給子組件,如果傳遞的參數(shù)很多,推薦使用json數(shù)組{}的形式
②定義子組件,子組件通過(guò) props方法獲取父組件傳遞過(guò)來(lái)的值。props中可以定義能接收的數(shù)據(jù)類型,如果不符合會(huì)報(bào)錯(cuò)。
當(dāng)然也可以簡(jiǎn)單一點(diǎn),如果不考慮數(shù)據(jù)類型,直接 props:["number","string"]就可以了,中括號(hào)包裹,多個(gè)值使用,分隔。
③假如接收的參數(shù) 是動(dòng)態(tài)的,比如 input輸入的內(nèi)容 v-model的形式
注意:傳遞的參數(shù)名稱 支持駝峰命名,下圖 描述不正確(1.0是不支持的)
④父子組件傳值,數(shù)據(jù)是異步請(qǐng)求,有可能數(shù)據(jù)渲染時(shí)報(bào)錯(cuò)
原因:異步請(qǐng)求時(shí),數(shù)據(jù)還沒(méi)有獲取到但是此時(shí)已經(jīng)渲染節(jié)點(diǎn)了
解決方案:可以在 父組件需要傳遞數(shù)據(jù)的節(jié)點(diǎn)加上 ?v-if = false,異步請(qǐng)求獲取數(shù)據(jù)后,v-if = true
(二)、子組件往父組件傳值,通過(guò)emit事件
四、不同組件之間傳值,通過(guò)eventBus(小項(xiàng)目少頁(yè)面用eventBus,大項(xiàng)目多頁(yè)面使用 vuex)
①定義一個(gè)新的vue實(shí)例專門用于傳遞數(shù)據(jù),并導(dǎo)出
②定義傳遞的方法名和傳輸內(nèi)容,點(diǎn)擊事件或鉤子函數(shù)觸發(fā)eventBus.emit事件
③接收傳遞過(guò)來(lái)的數(shù)據(jù)
注意:enentBus是一個(gè)另一個(gè)新的Vue實(shí)例,區(qū)分兩個(gè)this所代表得vue實(shí)例
五、vuex進(jìn)行傳值
為什么使用vuex?
vuex主要是是做數(shù)據(jù)交互,父子組件傳值可以很容易辦到,但是兄弟組件間傳值(兄弟組件下又有父子組件),或者大型spa單頁(yè)面框架項(xiàng)目,頁(yè)面多并且一層嵌套一層的傳值,異常麻煩,用vuex來(lái)維護(hù)共有的狀態(tài)或數(shù)據(jù)會(huì)顯得得心應(yīng)手。
需求:兩個(gè)組件A和B,vuex維護(hù)的公共數(shù)據(jù)是 餐館的名稱 resturantName,默認(rèn)餐館名稱是 飛歌餐館,那么現(xiàn)在A和B頁(yè)面顯示的就是飛歌餐館。如果A修改餐館名稱 為 A餐館,則B頁(yè)面顯示的將會(huì)是 A餐館,反之B修改同理。這就是vuex維護(hù)公共狀態(tài)或數(shù)據(jù)的魅力,在一個(gè)地方修改了數(shù)據(jù),在這個(gè)項(xiàng)目的其他頁(yè)面都會(huì)變成這個(gè)數(shù)據(jù)。
?????????? ? ? ?
①使用 vue-cli腳手架工具創(chuàng)建一個(gè)工程項(xià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>
②開(kāi)始使用vuex,新建一個(gè) sotre文件夾,分開(kāi)維護(hù) actions mutations getters
②在store/index.js文件中新建vuex 的store實(shí)例
*as的意思是 導(dǎo)入這個(gè)文件里面的所有內(nèi)容,就不用一個(gè)個(gè)實(shí)例來(lái)導(dǎo)入了。
③actions
// 給action注冊(cè)事件處理函數(shù)。當(dāng)這個(gè)函數(shù)被觸發(fā)時(shí)候,將狀態(tài)提交到mutations中處理 export function modifyAName({commit}, name) { // commit 提交;name即為點(diǎn)擊后傳遞過(guò)來(lái)的參數(shù),此時(shí)是 'A餐館'return commit ('modifyAName', name) } export function modifyBName({commit}, name) {return commit ('modifyBName', name) }// ES6精簡(jiǎn)寫法 // export const modifyAName = ({commit},name) => commit('modifyAName', name)④mutations
// 提交 mutations是更改Vuex狀態(tài)的唯一合法方法 export const modifyAName = (state, name) => { // A組件點(diǎn)擊更改餐館名稱為 A餐館state.resturantName = name // 把方法傳遞過(guò)來(lái)的參數(shù),賦值給state中的resturantName } export const modifyBName = (state, name) => { // B組件點(diǎn)擊更改餐館名稱為 B餐館state.resturantName = name }⑤getters
// 獲取最終的狀態(tài)信息 export const resturantName = state => state.resturantName⑥在main.js中導(dǎo)入 store實(shí)例
// 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中,定義點(diǎn)擊事件,點(diǎn)擊 修改 餐館的名稱,并把餐館的名稱在事件中用參數(shù)進(jìn)行傳遞。
?
...mapactions 和 ...mapgetters都是vuex提供的語(yǔ)法糖,在底層已經(jīng)封裝好了,拿來(lái)就能用,簡(jiǎn)化了很多操作。
其中...mapActions(['clickAFn']) 相當(dāng)于this.$store.dispatch('clickAFn',{參數(shù)}),mapActions中只需要指定方法名即可,參數(shù)省略。
...mapGetters(['resturantName'])相當(dāng)于this.$store.getters.resturantName
<template><div class="componentsA"><P class="title">組件A</P><P class="titleName">餐館名稱:{{resturantName}}</P><div><!-- 點(diǎn)擊修改 為 A 餐館 --><button class="btn" @click="modifyAName('A餐館')">修改為A餐館</button></div><div class="marTop"><button class="btn" @click="trunToB">跳轉(zhuǎn)到B頁(yè)面</button></div></div> </template><script> import {mapActions, mapGetters} from 'vuex' export default {name: 'A',data () {return {}},methods:{...mapActions( // 語(yǔ)法糖['modifyAName'] // 相當(dāng)于this.$store.dispatch('modifyName'),提交這個(gè)方法),trunToB () {this.$router.push({path: '/componentsB'}) // 路由跳轉(zhuǎn)到B}},computed: {...mapGetters(['resturantName']) // 動(dòng)態(tài)計(jì)算屬性,相當(dāng)于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><!-- 點(diǎn)擊修改 為 B 餐館 --><button class="btn" @click="modifyBName('B餐館')">修改為B餐館</button></div><div class="marTop"><button class="btn" @click="trunToA">跳轉(zhuǎn)到A頁(yè)面</button></div></div> </template><script> import {mapActions, mapGetters} from 'vuex' export default {name: 'B',data () {return {}},methods:{...mapActions( // 語(yǔ)法糖['modifyBName'] // 相當(dāng)于this.$store.dispatch('modifyName'),提交這個(gè)方法),trunToA () {this.$router.push({path: '/componentsA'}) // 路由跳轉(zhuǎn)到A}},computed: {...mapGetters(['resturantName']) // 動(dòng)態(tài)計(jì)算屬性,相當(dāng)于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>
---------------------?
轉(zhuǎn)自:https://blog.csdn.net/qq_35430000/article/details/79291287?
?
總結(jié)
以上是生活随笔為你收集整理的vue 通信、传值的多种方式(超详细)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: STM32工程建立
- 下一篇: Vue Google浏览器插件 Vue