vuex獲取state對象中值的所有方法小結(jié)(module中的state)
更新時間:2022年04月12日 10:41:10 作者:trenki
這篇文章主要介紹了vuex獲取state對象中值的所有方法小結(jié)(module中的state),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
vuex獲取state對象中的值
直接從store實例取值
// main.js中,把store注冊在根實例下,可使用this.$stroe.state直接取值 export default { ? computed: { ? ? testNum() { ? ? ? return this.$store.state.testNum; ? ? } ? } };
使用mapState取值的多種方法
import { mapState } from "vuex";export default { ? data() { ? ? return { localNum: 1 }; ? }, ? computed: { ? ? ...mapState({ ? ? ? // 箭頭函數(shù)使代碼更簡練 ? ? ? testNum1: state => state.testNum1, ? ? ? // 傳字符參數(shù)'testNum2' 等價于 'state => state.testNum2' ? ? ? testNum2: "testNum2", ? ? ? // 組件的局部變量與Vuex變量相加 ? ? ? testNum3(state) { ? ? ? ? return state.testNum1 + this.localNum; ? ? ? } ? ? }), ? ? ...mapState([ ? ? ? // 映射this.testNum3為store.state.testNum3 ? ? ? "testNum3" ? ? ]) ? } };
使用module中的state
import { mapState } from "vuex"; export default { ? computed: { ? ? ...mapState({ ? ? ? // 箭頭函數(shù)使代碼更簡練 ? ? ? testNum1: state => state.moduleA.testNum1 ? ? }), ? ? // 第一個參數(shù)是namespace命名空間,填上對應(yīng)的module名稱即可 ? ? ...mapState("moduleA", { ? ? ? testNum2: state => state.testNum2, ? ? ? testNum3: "testNum3" ? ? }), ? ? ...mapState("moduleA",[ ? ? ? "testNum4" ? ? ]) ? } };
vuex調(diào)用state數(shù)據(jù)
第一種
直接訪問 <h1>姓名:{{$store.state.msg}}</h1>
第二種:利用計算屬性
將想要用到的全局state數(shù)據(jù),防止到組件的computed內(nèi)部使用,v-model的內(nèi)容將其獲取和設(shè)置分開即可
<h1>姓名:{{msg}}</h1> <h1>年齡:{{age}}</h1> <h1>數(shù)字:{{num}}</h1> <input type="text" v-model="num"> computed: { ????????age:function(){??//msg也相同,就沒寫 ????????????return this.$store.state.age ????????}, ????????num:{ ????????????get:function(){ ????????????????return this.$store.state.num; ????????????}, ????????????set:function(num){?? //數(shù)據(jù)雙向綁定 ????????????????this.$store.commit('setNum',num) ????????????} ????????} ????},
第三種:mapstate 數(shù)組
<h1>姓名:{{msg}}</h1> <h1>年齡:{{age}}</h1> <h1>數(shù)字:{{num}}</h1> <input type="text" :value="num" @input="changeVal" > import { mapState } from 'vuex'??//需要引入mapState computed:mapState(['age','msg','num']), ????methods: {?? ????????changeVal(e){????//設(shè)置值 ????????????return this.$store.commit('setNum',e.target.value) ????????} ????},
第四種:mapState 對象
<h1>姓名:{{msg}}</h1> <h1>年齡:{{age}}</h1> <h1>數(shù)字:{{num}}</h1> import { mapState } from 'vuex'??//需要引入mapState computed:mapState({ ????????msg:'msg', ????????num:'num', ????????// age:(state)=>state.age,?? //不需要大括號的時候,就不需要用 return 返回值 ????????age:(state)=>{ return state.age}, ????})
第五種:mapState 對象 解構(gòu) 追加變量
<h1>姓名:{{msg}}</h1> <h1>年齡:{{age}}</h1> <h1>數(shù)字:{{num}}</h1> import { mapState } from 'vuex' let objMapState=mapState({ ????????msg:'msg', ????????num:'num', ????????// age:(state)=>state.age, ????????age:function(state){ return this.greenColor+state.age}, ????}) data() { ????????return { ????????????greenColor:'blue'???????????? ????????} ????}, computed:{ ????????...mapState(objMapState) ????}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。