vue內部資料流程圖

vue與組件之間的資料互動

一.如何使用全域State?
//state的作用是存盤公共資料
//state是回應式的,如果修改了屬性,那么在相對應,組件視圖上的值也會改變
//在store里定義格式
new Vuex.store({
state: {
屬性名: 屬性值
}
})
//在組件中使用格式
this.$store.state.屬性名
//在模板中可省略this
{{$store.state.屬性名}}
//在組件中使用map輔助函式:
computed: {
...mapState(['屬性名']),
...mapState({'新名字': '屬性名'})
}
如何使用modules中的state?
//使用在modules中的state
this.$store.state.moudules模塊名.xxx
//使用map輔助函式:
computed: {
...mapState('模塊名', ['屬性名']),
...mapState('模塊名', {'新名字': '屬性名'})
}
二.如何使用全域getters?
//在store里定義getters
new Vuex.store({
// 省略其他...
getters: {
// state 就是上邊定義的公共資料state
getter的名字1: function(state) { //state 就是上邊定義的公共資料state
return 要回傳的值
}
}
})
//在組件中使用:
this.$store.getters.getter的名字
//使用map輔助函式:
computed: {
...mapGetters(['getters的名字']),
...mapGetters({'新名字': 'getters的名字'})
}
如何使用modules中的getters?
//使用modules中的屬性
{{$store.gerters.模塊名.資料項名}}
//使用map輔助函式:
computed: {
...mapGetters('模塊名', ['資料項名']),
...mapGetters('模塊名',{'新名字': '資料項名'})
}
三.如何使用全域mutations?
//在store里定義mutations
new Vue.store({
// 省略其他...
mutations:{
// 每一項都是一個函式,可以宣告兩個形參
mutation名1:function(state [, 載荷]) {
},
mutation名2:function(state [, 載荷]) {
},
}
})
//在組件中使用:
this.$store.commit('mutation資料項名', 引數) //這里的commit是固定的方法
//使用map輔助函式:
methods: {
...mapMutations(['mutation資料項名']),
...mapMutations({'新名字': 'mutation資料項名'})
}
如何使用modules中的mutations(namespaced:true)?
//使用modules中的屬性
{{$store.commit('模塊名/mutations資料項名',引數)}}
//使用map輔助函式:
methods: {
...mapMutations('模塊名', ['mutations資料項名']),
...mapMutations('模塊名',{'新名字': 'mutations資料項名'})
}
四.如何使用全域actions?
//在store里定義actions
new Vuex.store({
// 省略其他...
actions: {
// context物件會自動傳入,它與store實體具有相同的方法和屬性
action的名字: function(context, 載荷) {
// 1. 發異步請求, 請求資料
// 2. commit呼叫mutation來修改/保存資料
// context.commit('mutation名', 載荷)
}
}
})
//在組件中使用
this.$store.dispatch('actions的名字', 引數)
//使用map輔助函式:
methods: {
...mapActions(['actions的名字']),
...mapActions({'新名字': 'actions的名字'})
}
如何使用modules中的actions(namespaced:true)?
//使用modules中的屬性:
{{$store.dispatch('模塊名/actions資料項名',引數)}}
//使用map輔助函式:
methods: {
...mapActions('模塊名', ['actions資料項名']),
...mapActions('模塊名',{'新名字': 'actions資料項名'})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/303901.html
標籤:其他
上一篇:產品經理:你能不能讓詞云動起來?
