前言:
六種傳值方式為:
- 屬性傳值
- $refs
- $parent
- 通知傳值(廣播傳值)
- 本地傳值
- 路由傳值
在介紹組件傳值之前先明確三種組件關(guān)系:父子組件扁达、兄弟組件滑肉、無(wú)關(guān)系組件
上圖關(guān)系基于:A谅畅、B組件同一時(shí)刻只存其一的情況下归苍,其中:
- A是C、D笔呀、E的父組件镜粤,B是F捏题、G、H的父組件
- C肉渴、D公荧、E是A的子組件,F(xiàn)同规、G循狰、H是B的子組件
- C和D、E是兄弟組件券勺,F(xiàn)和G晤揣、H是兄弟組件。但E朱灿、F不是兄弟組件
- A和B是無(wú)關(guān)系組件,E和F也是無(wú)關(guān)系組件
一钠四、屬性傳值
1.可傳值類型
- 固定值
- 綁定屬性
- 方法
- 本類對(duì)象
2.操作步驟
①.父組件調(diào)用子組件的時(shí)候盗扒,綁定動(dòng)態(tài)屬性 <htitle mess="父組件給子組件傳值"></htitle>
②. 在子組件里邊通過props,接收父組件傳過來的值
3.適用場(chǎng)景
僅適用于 父組件給子組件傳值
4.屬性介紹
組件屬性定義:
props:["mess","bindMsg","run","fatherThis"],
子組件驗(yàn)證也可傳入?yún)?shù)的合法性:
props:{
'mess':String,
'bindMsg':[String, Number],
'run':Function,
'fatherThis':Object,
}
更多props請(qǐng)查看Vue官網(wǎng):https://cn.vuejs.org/v2/api/?#props
5.示例代碼
父組件:
<template>
<div id="app">
<htitle mess="父組件給子組件傳值了" :bindMsg="msg" :run="run" :fatherThis="this"></htitle>
</div>
</template>
子組件
<template>
<div class="divfirst">
<span>{{mess}}</span>
<h1>{{bindMsg}}</h1>
<button @click="run()">點(diǎn)擊調(diào)用父組件方法</button>
<button @click="getPrasent()">點(diǎn)擊獲取父組件實(shí)體(實(shí)體拿到可以使用用父組件的方法和屬性了)</button>
</div>
</template>
<script>
export default {
props:{
'mess':String,
'bindMsg':[String, Number],
'run':Function,
'fatherThis':Object,
},
data(){
return {}
},
methods:{
getPrasent(){
this.fatherThis.run();
alert(this.fatherThis.msg);
}
}
}
</script>
二、父組件獲取子組件數(shù)據(jù)
?父組件通過$refs獲取子組件的數(shù)據(jù)和方法
1.可獲取類型
- 子組件屬性
- 子組件方法
2.操作步驟
1.調(diào)用子組件的時(shí)候調(diào)用一個(gè)ref
<v-fgsheader ref="header"></v-fgsheader>
2.在父組件中通過
this.$refs.header.屬性
this.$refs.header.方法
3.適用場(chǎng)景
子組件給父組件傳值
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>
三缀去、子組件獲取父組件數(shù)據(jù)
??子組件通過$parent獲取父組件的數(shù)據(jù)和方法侣灶,這種傳值方式實(shí)際上類似于上邊的屬性傳值中父組件給子組件的傳遞了子類對(duì)象this
,只不過Vue官方給封裝好了。
1.可獲取類型
- 父組件屬性
- 父組件方法
2.操作步驟
直接在子組件中使用this.$parent.XX
缕碎,不需要做任何多余操作褥影。
3.適用場(chǎng)景
父組件給子組件傳值
4.示例代碼
子組件
getFatherProp(){
alert(this.$parent.fatherMsg);
},
getFatherMethod(){
this.$parent.fatherRun();
}
四、通知傳值(廣播傳值)
1.可傳值類型
Vue官網(wǎng)只寫了[...args]
咏雌,故通知/廣播傳值我們定為只傳基本數(shù)據(jù)類型凡怎,不能傳方法校焦。
2.操作步驟
1、新建一個(gè)js文件 然后引入vue 實(shí)例化vue 最后暴露這個(gè)實(shí)例
2统倒、在要廣播的地方引入剛才定義的實(shí)例
3寨典、通過 VueEmit.$emit('名稱','數(shù)據(jù)')傳播數(shù)據(jù)
4、在接收收數(shù)據(jù)的地方通過 $on接收廣播的數(shù)據(jù)
VueEmit.$on('名稱',function(){})
3.適用場(chǎng)景
適用于父子組件房匆、兄弟組件間進(jìn)行傳值耸成。
無(wú)關(guān)系組件不能用這種方式傳值。(筆者理解是:對(duì)于上圖中的A浴鸿、B組件井氢。假設(shè)A廣播通知,B接收通知岳链。掛載A的時(shí)候B卸載了花竞,也就是說B被內(nèi)存銷毀了,B是接收不到廣播的)
4.屬性介紹
對(duì)于通知傳值而言,可以一人廣播宠页,然后多者接收左胞。
5.示例代碼
vueEvent.js
import Vue from 'vue'
var vueEvents = new Vue();
export default vueEvents;
兄弟組件C(廣播者)
import vueEvents from '../Model/vueEvent.js'
sendEmit(){
var numbery = (Math.random()+300).toFixed(3);
vueEvents.$emit('notifyToNew',this.homeMsg+numbery);
}
兄弟組件D(接收者)
import vueEvents from '../Model/vueEvent.js'
mounted(){
var _this = this;
vueEvents.$on("notifyToNew",function(data_P){
//注意this的作用域
console.log('廣播傳過來的值是'+data_P);
_this.receive = data_P;
})
}
五、本地傳值
本地傳值方式對(duì)于Vue而言有兩種举户,一種是JS的localStorage
烤宙,另一種Vuex
。
1.可傳值類型
localStorage
: String(可通過JSON
進(jìn)行json數(shù)據(jù)與String之間的轉(zhuǎn)化)
Vuex
:方法俭嘁、數(shù)據(jù)躺枕、異步方法
2.操作步驟
2.1 localStorage
存:
localStorage.setItem('tolist',JSON.stringify(this.tolist));
取:
var tolist = JSON.parse(localStorage.getItem('tolist'));
2.2 Vuex
2.1 src新建一個(gè)vuex文件夾
2.2 vuex文件夾里新建一個(gè)store.js
2.3 安裝vuex cnpm install vuex --save
2.4 在剛才創(chuàng)建的store.js 中引入vue供填、vuex 引入vuex 并且use
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
2.5 定義數(shù)據(jù) state在vuex中用于存儲(chǔ)數(shù)據(jù)
var state = { count:1,}
2.6 定義方法 mutations里邊放的是方法,方法主要用于改變state里邊的數(shù)據(jù)
var mutations = {
incCount(){
++state.count;
}
}
//類似于計(jì)算屬性 state里邊的數(shù)據(jù)改變時(shí)候觸發(fā)的方法拐云。 可以做一些操作 并且可以有返回值
var getterfl={
completedCountChange(state){
return state.count * 2 +'位';
}
}
Action 類似于 mutation,不同在于: Action 提交的是 mutation近她,而不是直接變更狀態(tài)叉瘩。Action 可以包含任意異步操作
var actionfl = {
asynIncCount(context){
//因此你可以調(diào)用context.commit來提交一個(gè)mutation 使用action需要用dispatch
context.commit('incCount');
}
}
2.7 實(shí)例化 vuex
const store = new Vuex.Store({
state,//state: state 簡(jiǎn)寫
mutations: mutations,//屬性的簡(jiǎn)寫是 mutations
getters:getterfl,
actions:actionfl,
})
2.8 對(duì)外暴露
export default store;
2.9 在需要用的地方引入
import store from '../vuex/store.js'
2.10 注冊(cè)store ,放在methods,data同級(jí)
export default {
data(){
return{}
},
store:store,
methods:{
incCount(){
this.$store.commit('incCount');
}
}
}
2.11 使用vuex
使用數(shù)據(jù): this.\$store.state.count
調(diào)用方法: this.$store.commit('incCount');
3.適用場(chǎng)景
父子組件粘捎、兄弟組件薇缅、無(wú)關(guān)系組件任意組件之間的傳值
4.品鑒
Vuex本質(zhì)上也是一種本地存儲(chǔ),比localStorage
的單純值傳遞多了方法攒磨、屬性泳桦、異步方法等功能。但是因?yàn)槭菍?nèi)容本地化娩缰,所以就會(huì)被在瀏覽器中獲取到灸撰。
六、路由傳值
1.父組件push使用this.$router.push
2.在子組件中獲取參數(shù)的時(shí)候是this.$route.params
1 、動(dòng)態(tài)路由傳值
1.1 配置動(dòng)態(tài)路由
routes:[
//動(dòng)態(tài)路由參數(shù) 以冒號(hào)開頭
{path:'/user/:id',conponent:User}
]
1.2 傳值
第一種寫法 : <router-link :to="'/user/'+item.id">傳值</router-link>
第二種寫法 : goToUser(id) {
this.$router.push( {path:'/user/'+id});
}
1.3 在對(duì)應(yīng)頁(yè)面取值
this.$route.params; //結(jié)果:{id:123}
2浮毯、 Get傳值(類似HTMLGet傳值)
2.1 配置路由
const routes = [{path:'/user',component:User},]
2.2 傳值
第一種寫法 : <router-link :to="'/user/?id='+item.id">傳值</router-link>
第二種寫法 : goToUser(id) {
//'user' 是路徑名稱
this.$router.push({path:'user',query:{ID:id}});
}
2.3 在對(duì)應(yīng)頁(yè)面取值
this.$route.query; //結(jié)果 {id:123}
Tips:路徑傳遞參數(shù)會(huì)拼接在URL路徑后
3 完疫、命名路由push傳值
3.1 配置路由
const routes = [{path:'/user',name: 'User',component:User},]
3.2 傳值
goToUser(id) {
//'User' 是路徑重命名
this.$router.push({name:'User',params:{ID:id}});
}
3.3 在對(duì)應(yīng)頁(yè)面取值
this.$route.params; //結(jié)果:{id:123}
Tips:命名路由傳遞參數(shù)不在URL路徑拼接顯示
結(jié)束語(yǔ)
單一組件間建議使用屬性傳值單,一對(duì)多傳值建議廣播傳值亲轨,路由傳值需配合路由進(jìn)行處理趋惨,全局性的值(敏感信息除外)使用本地緩存?zhèn)髦怠8缸咏M件間傳值使用$refs惦蚊、$parent器虾。組件各種傳值方式各有優(yōu)劣,諸君請(qǐng)按實(shí)際情況選取蹦锋。