学习vue——vuex

东方不败--Never / 2024-09-26 / 原文

一、获取公共数据

state/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        count: 100,
        title: 'zd'
    }
})

export default store

html 的获取方式

// 方法一
<h5>{{ $store.state.count }}</h5>
// 方法二(简写模式)
<h4>{{ count }}-{{ title }}</h4>
import { mapState } from 'vuex'
computed:{
...mapState(['count','title'])
},
 js 获取
created(){
  console.log(this.$store.state.count)
}

 

二、修改公共数据(mutations)

state/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        count: 100,
        title: 'zd'
    },
    mutations: {
        updateCount(state,val){
            state.count += val
        }
    }

})

export default store
this.$store.commit('updateCount',20)
created(){
    console.log(this.$store.state.count)
    this.$store.commit('updateCount',20)
    console.log(this.$store.state.count)
  }
简写:...mapMutations(['updateCount'])
<button @click="useFaction">ues</button>
import { mapState,mapMutations } from 'vuex'
methods:{
...mapMutations(['updateCount']),
useFaction(){
this.updateCount(11)
}
},

 

三、

四、