在终端输入
vue ui
然后再打开浏览器,在浏览器里创建相关的项目,配置的步骤内容跟脚手架的差不多。
在components文件中创建add.vue和sub.vue这两个文件,
打开store/index.js
app.vue
<template>
<div id="app">
<Add />
<Sub />
</div>
</template>
<script>
import Add from '@/components/add'
import Sub from '@/components/sub'
export default {
components: {
Add,
Sub
}
}
</script>
<style lang="less"></style>
add.vue
<template>
<div>
<!-- <h3>当前最新的count值为:{{ this.$store.state.count }}</h3> -->
<!-- 此处的count是变量 -->
<h3>当前最新的count值为:{{ count }}</h3>
<button @click="add">+1</button>
<button @click="addsync">+1addsync</button>
</div>
</template>
<script>
// 导入
import { mapState } from 'vuex'
export default {
methods: {
add() {
// commit()的第一个参数是store/index.js中mutations的add函数,第二个参数1是传过去的数据,是js中的num接收
// commit来访问mutations里面的方法
// add的commit里面不传参
this.$store.commit('add')
},
addsync() {
// dispatch来访问actions里面方法
this.$store.dispatch('addSync', 1)
}
},
// 计算属性
computed: {
...mapState(['count'])
}
}
</script>
<style></style>
sub.vue
<template>
<div>
<!-- 这里是count是属性 -->
<h3>当前最新的count值为:{{ showCount }}</h3>
<button @click="subb">-1</button>
<button @click="subsync()">-1addsync</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
methods: {
// mapMutations对sub进行解构了
...mapMutations(['sub']),
...mapActions(['subSync']),
subb() {
// this.$store.commit('sub', 1)
// 所以这里可以直接使用了,click调用时直接传值
this.sub()
},
subsync() {
// dispatch来访问actions里面方法
// this.$store.dispatch('subSync', 1)
this.subSync()
}
},
computed: {
...mapState(['count']),
...mapGetters(['showCount'])
}
}
</script>
<style></style>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 里面存放的是公共的,可以空享的数据
// 变量
state: {
count: 0
},
// 只有mutations才能修改state(状态)中的数据
// 方法
mutations: {
// 第一个参数一定是state,num是vue文件中传过来的传过来的值
// vue文件没有传参过来,就不用第二个参数来接收
add(state) {
// state.count += num
state.count += 1
},
sub(state) {
state.count -= 1
}
},
// 操作异步代码,但是不能操作状态(state)中的变量,如果需要操作,可以在mutations中创建相关函数来操作state中的变量,然后在actions中再调用该函数即可
actions: {
// context:上下文
addSync(context, num) {
// setTimeout是异步的
setTimeout(() => {
// 在actions里面不能修改state里面的数据,所以调用mutations中的方法
context.commit('add', num)
// console.log(context)
}, 1000)
},
subSync(context) {
setTimeout(() => {
context.commit('sub')
}, 1000)
}
},
getters: {
showCount(state) {
return '这是我最后一次操作count:' + state.count
}
},
modules: {}
})