Vuex使用

使用Vuex

store index.js

import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex)
export default new Vuex.Store({
    state:{
        count:1
    },
    getters:{

    },
    // 用于修改state数据的方法
    mutations:{
   
    },
    actions:{

    },
    modules:{

    }
})

index.vue

<template>
  <div>
      <h1>{{count}}</h1>
  </div>
</template>

<script>
export default {
    data() {
        return {
            
        }
    },
    computed:{
        count(){
          return this.$store.state.count
           
        }
    }
    
}
</script>

<style>

</style>
image.png

使用辅助函数

<template>
  <div>
      <h1>{{count}}</h1>
      <h2>{{count2}}</h2>

  </div>
</template>

<script>
import {mapState} from "vuex";
export default {
    data() {
        return {
            
        }
    },
    computed:{
      ...mapState({
        count(state){
          return state.count 
        },
        count2(state){
          return state.count2
        }
      })
        
    }
    
}
</script>

<style>

</style>

使用mutations实现计数器效果

store index.js

import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex)
export default new Vuex.Store({
    state:{
        count:1
    },
    getters:{

    },
    // 用于修改state数据的方法
    mutations:{
        increment(state,n){
            state.count+=n
        },
        reduce(state,n){
            state.count-=n
        }
    },
    actions:{

    },
    modules:{

    }
})
<template>
  <div class="content">
      <button @click="$store.commit('reduce',1)">-1</button>
      <h1>{{count}}</h1>
      <button @click="$store.commit('increment',1)">+1</button>

  </div>
</template>

<script>
export default {
    data() {
        return {
            
        }
    },
    computed:{
      count(){
        return this.$store.state.count
      }
        
    }
    
}
</script>

<style>
  .content{
    display: flex;
  }
  h1{
    margin: 0 20px;
  }
  button{
    width: 100px;
    height: 40px;
  }
</style>
2021-12-08-21-15-50.gif
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容