Vuex中調用state數據


第一種:直接訪問 <h1>姓名:{{$store.state.msg}}</h1>

第二種:利用計算屬性

將想要用到的全局state數據,防止到組件的computed內部使用,v-model的內容將其獲取和設置分開即可

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<h1>姓名:{{msg}}</h1>

<h1>年齡:{{age}}</h1>

<h1>數字:{{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){   //數據雙向綁定

                this.$store.commit('setNum',num)

            }

        }

    },

第三種:mapstate 數組

 

1

2

3

4

5

6

7

8

9

10

11

12

13

<h1>姓名:{{msg}}</h1>

<h1>年齡:{{age}}</h1>

<h1>數字:{{num}}</h1>

<input type="text" :value="num" @input="changeVal" >

 

import { mapState } from 'vuex'  //需要引入mapState

 

computed:mapState(['age','msg','num']),

    methods: {  

        changeVal(e){    //設置值

            return this.$store.commit('setNum',e.target.value)

        }

    },

第四種:mapState 對象

 

1

2

3

4

5

6

7

8

9

10

11

12

<h1>姓名:{{msg}}</h1>

<h1>年齡:{{age}}</h1>

<h1>數字:{{num}}</h1>

 

import { mapState } from 'vuex'  //需要引入mapState

 

computed:mapState({

        msg:'msg',

        num:'num',

        // age:(state)=>state.age,   //不需要大括號的時候,就不需要用 return 返回值

        age:(state)=>{ return state.age},

    })

第五種:mapState 對象 解構 追加變量

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

 

<h1>姓名:{{msg}}</h1>

<h1>年齡:{{age}}</h1>

<h1>數字:{{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)

    }

 

Vuex中調用state數據

Go: 一點博客-青梅煮碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM