Vuex中调用state数据


第一种:直接访问 <h1>姓名:{{$store.state.msg}}</h1>

第二种:利用计算属性

将想要用到的全局state数据,防止到组件的computed内部使用,v-model的内容将其获取和设置分开即可

<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 数组

<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 对象

<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 对象 解构 追加变量


<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)
    }

b8d6eab01a2250f57287cd8bf5ba58f1-1

,

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注