vuex的state中的数据的四种使用方法


store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
    count: 1
}
export default new Vuex.Store({
    state,mutations
})
  1. 直接通过$store来使用
<template>
  <div>
      <h3>{{msg}}</h3>
      <hr/>
      <h3>{{$store.state.count}}</h3>
</button>
  </div>
</template>

<script>
import store from '@/vuex/store'
export default {
    data(){
        return{
            msg:"hello vuex"
        }
    },
    store
}
</script>
<style>
</style>
  1. 通过computed添加一个计算属性来使用
<template>
  <div>
      <h3>{{$store.state.count}}------{{count}}</h3>
      <hr/>
  </div>
</template>

<script>
import store from '@/vuex/store'
import {mapState} from 'vuex'
export default {
    data(){
        return{
            msg:"hello vuex"
        }
    },
     computed:{
         count(){
             return this.$store.state.count
         }
	},
    store
}
</script>
<style>
</style>
  1. 通过computed+mapState返回函数的方法来使用
<template>
  <div>
      <h3>{{$store.state.count}}------{{count}}</h3>
      <h3>{{$store.state.count}}------{{a}}</h3>
      <hr/>
      <p>
          <button @click="$store.commit('add')">+</button>
          <button @click="$store.commit('reduce')">-</button>
      </p>
  </div>
</template>

<script>
import store from '@/vuex/store'
import {mapState} from 'vuex'
export default {
    data(){
        return{
            msg:"hello vuex"
        }
    },
        computed: mapState({
             count:state=>state.count
         }),
    store
}
</script>
<style>
</style>
  1. 通过computed+mapState的数组来使用
<template>
  <div>
      <h3>{{$store.state.count}}------{{count}}</h3>
      <h3>{{$store.state.count}}------{{a}}</h3>
      <hr/>
      <p>
          <button @click="$store.commit('add')">+</button>
          <button @click="$store.commit('reduce')">-</button>
      </p>
  </div>
</template>

<script>
import store from '@/vuex/store'
import {mapState} from 'vuex'
export default {
    data(){
        return{
            msg:"hello vuex"
        }
    },
    //名称要与state中的数据属性名称相同
    computed:{...mapState(['count'])},
    store
}
</script>
<style>
</style>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM