使用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