Vuex
1.state的使用
首先在src文件夾下面建一個(gè)store文件夾作為倉(cāng)庫(kù)
store里創(chuàng)建一些js文件作為相對(duì)應(yīng)的存儲(chǔ)空間
例如 store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.store({
state: { //狀態(tài)管理
count: 1
},
getters: { //獲取狀態(tài)值
getCount: function(state){
return state.count * 5
}
},
mutations: { //操作狀態(tài)
add: function(state){
state.count += 1
}
},
actions: { //異步操作狀態(tài)
addFun: function(context){
context.commit('add')
}
}
})
在vue組件中使用
在插值表達(dá)式里 {{$store.state.count}}
computed:{
count(){
return this.$store.state.count
}
}
更新state的值
methods: {
change(){
this.$store.commit('add',args) //同步操作,可以有選擇性的傳參
},
asyncChange() {
this.$store.dispatch('addFun') //異步操作
}
}
2.mapState的使用
1.在.vue組件中引入,在js塊中引入
import { mapState } from 'vuex'
2.在.vue組件中使用,一般放在computed里可以監(jiān)聽(tīng)到狀態(tài)改變
computed:{
...mapState([ //mapState本是一個(gè)函數(shù),在里面寫(xiě)一個(gè)數(shù)組,記得加...
‘num’ , //存的數(shù)據(jù)
‘id’
])
}
或
computed: {
...mapState({
num: (state)=>state.num, //這種用法可以看作為起別名
id: (state)=>state.id
})
}
mapAction的使用
正常action的使用
this.$store.dispatch('function',args)
mapAction
import {mapActions} from 'vuex'
methods: {
...mapActions(['fun1','fun2','fun3'])
或
...mapActions({
fun1: 'fun1',
fun2: 'fun2'
})
}
mapMutations的使用 //關(guān)于傳參問(wèn)題,直接在調(diào)用的地方傳參
正常mutation的使用
this.$store.commit('function',args)
mapMutations的使用
import {mapMutations} from 'vuex'
methods:{
...mapMutations(['fun1','fun2'])
或
...mapMutations({
fun1: 'fun1',
fun2: 'fun2'
})
}
混入 (mixin)
混入 (mixin) 提供了一種非常靈活的方式,來(lái)分發(fā) Vue 組件中的可復(fù)用功能。一個(gè)混入對(duì)象可以包含任意組件選項(xiàng)。當(dāng)組件使用混入對(duì)象時(shí),所有混入對(duì)象的選項(xiàng)將被“混合”進(jìn)入該組件本身的選項(xiàng)。
組件的思想主要是用來(lái)解決重復(fù)碼有相似功能的代碼,并使其標(biāo)準(zhǔn)化,統(tǒng)一化,但在前端更多是體現(xiàn)在界面上的視覺(jué)效果,如果要實(shí)現(xiàn)功能大體相同,界面需要個(gè)性化,但又不想傳入過(guò)多的props怎么辦呢
這時(shí)mixin便有了其用武之地,可以使用相同的js邏輯,template和css自定義就好了
具體使用:
先在src下建一個(gè)文件夾mixin
然后在該文件夾下創(chuàng)建你需要按功能取名的js文件
例如common.js
const toggle = { //你需要引入哪些就加哪些
data(){
return {}
},
created(){},
methods:{}
... //還可以添加
}
export toggle
在.vue文件中使用
import { toggle } from '@/mixin/common.js'
export default {
mixins: [toggle]
}
注意:如果混入里的東西和組件內(nèi)的有沖突,會(huì)使用組件內(nèi)的,欲安內(nèi)必先攘外
全局混入
在main.js中定義
Vue.mixin({
created: function () {
}
... // 省略
})