六種傳值方式為:
- 屬性傳值
- $refs
- $parent
- 通知傳值(廣播傳值)
- 本地傳值
- 路由傳值
一、屬性傳值
1.可傳值類型
- 固定值
- 綁定屬性
- 方法
- 本類對象
2.操作步驟
①.父組件調用子組件的時候,綁定動態屬性 <htitle mess="父組件給子組件傳值"></htitle>
②. 在子組件里邊通過props,接收父組件傳過來的值
3.適用場景
僅適用於 父組件給子組件傳值
4.屬性介紹
組件屬性定義:
props:["mess","bindMsg","run","fatherThis"],
子組件驗證也可傳入參數的合法性:
props:{ 'mess':String, 'bindMsg':[String, Number], 'run':Function, 'fatherThis':Object, }
更多props請查看Vue官網: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()">點擊調用父組件方法</button>
<button @click="getPrasent()">點擊獲取父組件實體(實體拿到可以使用用父組件的方法和屬性了)</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>
二、父組件獲取子組件數據
父組件通過$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();
}
四、通知傳值(廣播傳值)
1.可傳值類型
Vue官網只寫了[...args]
,故通知/廣播傳值我們定為只傳基本數據類型,不能傳方法。
2.操作步驟
1、新建一個js文件 然后引入vue 實例化vue 最后暴露這個實例
2、在要廣播的地方引入剛才定義的實例
3、通過 VueEmit.$emit('名稱','數據')傳播數據
4、在接收收數據的地方通過 $on接收廣播的數據
VueEmit.$on('名稱',function(){})
3.適用場景
適用於父子組件、兄弟組件間進行傳值。 無關系組件不能用這種方式傳值。(筆者理解是:對於上圖中的A、B組件。假設A廣播通知,B接收通知。掛載A的時候B卸載了,也就是說B被內存銷毀了,B是接收不到廣播的)
4.屬性介紹
對於通知傳值而言,可以一人廣播,然后多者接收。
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;
})
}
五、本地傳值
本地傳值方式對於Vue而言有兩種,一種是JS的localStorage
,另一種Vuex
。
1.可傳值類型
localStorage
: String(可通過JSON
進行json數據與String之間的轉化)Vuex
:方法、數據、異步方法
2.操作步驟
2.1 localStorage
存:
localStorage.setItem('tolist',JSON.stringify(this.tolist));
取:
var tolist = JSON.parse(localStorage.getItem('tolist'));
2.2 Vuex
2.1 src新建一個vuex文件夾
2.2 vuex文件夾里新建一個store.js
2.3 安裝vuex cnpm install vuex --save
2.4 在剛才創建的store.js 中引入vue、vuex 引入vuex 並且use
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
2.5 定義數據 state在vuex中用於存儲數據
var state = { count:1,}
2.6 定義方法 mutations里邊放的是方法,方法主要用於改變state里邊的數據
var mutations = { incCount(){ ++state.count; } } //類似於計算屬性 state里邊的數據改變時候觸發的方法。 可以做一些操作 並且可以有返回值 var getterfl={ completedCountChange(state){ return state.count * 2 +'位'; } }
Action 類似於 mutation,不同在於: Action 提交的是 mutation,而不是直接變更狀態。Action 可以包含任意異步操作
var actionfl = { asynIncCount(context){ //因此你可以調用context.commit來提交一個mutation 使用action需要用dispatch context.commit('incCount'); } }
2.7 實例化 vuex
const store = new Vuex.Store({ state,//state: state 簡寫 mutations: mutations,//屬性的簡寫是 mutations getters:getterfl, actions:actionfl, })
2.8 對外暴露
export default store;
2.9 在需要用的地方引入
import store from '../vuex/store.js'
2.10 注冊store ,放在methods,data同級
export default { data(){ return{} }, store:store, methods:{ incCount(){ this.$store.commit('incCount'); } } }
2.11 使用vuex
使用數據: this.\$store.state.count
調用方法: this.$store.commit('incCount');
3.適用場景
父子組件、兄弟組件、無關系組件任意組件之間的傳值
4.品鑒
Vuex本質上也是一種本地存儲,比localStorage
的單純值傳遞多了方法、屬性、異步方法等功能。但是因為是將內容本地化,所以就會被在瀏覽器中獲取到。
六、路由傳值
1.父組件push使用this.$router.push
2.在子組件中獲取參數的時候是this.$route.params
1 、動態路由傳值
1.1 配置動態路由 routes:[ //動態路由參數 以冒號開頭 {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 在對應頁面取值 this.$route.params; //結果:{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 在對應頁面取值 this.$route.query; //結果 {id:123}
Tips:路徑傳遞參數會拼接在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 在對應頁面取值 this.$route.params; //結果:{id:123}
Tips:命名路由傳遞參數不在URL路徑拼接顯示
結束語
單一組件間建議使用屬性傳值單,一對多傳值建議廣播傳值,路由傳值需配合路由進行處理,全局性的值(敏感信息除外)使用本地緩存傳值。父子組件間傳值使用$refs、$parent。組件各種傳值方式各有優劣,諸君請按實際情況選取。