前言
vue2 对应vuex 3版本,别下错了。
安装
npm i vuex@3.4.0
在main.js中
import store from './store'
new Vue({
router,
store, // 将store挂载到app上
render: h => h(App)
}).$mount('#app')
新建store文件
在src根目录下新建store文件夹,新建index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 创建一个新的 store 实例, 并默认导出
export default new Vuex.Store({
state: {
count: 1,
info: 'state.info',
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: { // 相当于 计算属性
getInfo: state => {
return '这是get获取来的数据:' + state.info;
},
getTodos: state => {
return state.todos.filter(todo => todo.done);
}
},
mutations: { // 同步的
addCount(state) {
state.count++;
},
minCount(state) {
state.count--;
},
amountCount(state, payload) {
state.count = payload.num
},
asyncAddCount(state) {
state.count++;
}
},
actions: { // 跟mutations相似,可以异步的
asyncCount(content) {
setTimeout(() => {
content.commit('asyncAddCount');
}, 2000);
}
}
})
使用示例
<template>
<div>
Vuex 页面:
<!-- state 使用方法 -->
<div>{{ count }}</div>
<!-- mutations 使用方法 -->
<button @click="add">点击加加</button>
<button @click="min">点击减减</button>
<button @click="amount({num: 10})">等于10</button>
<!-- getter 使用方法 -->
<div>{{ getInfo }}</div>
<div>{{ getTodos }}</div>
<!-- actions 使用方法 -->
<button @click="asyncHandler">异步执行</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
computed: {
...mapState(['count']), // 通过辅助函数获取 state 数据
...mapGetters(['getInfo', 'getTodos']) // getter使用方法
},
methods: {
// 提交告诉给 addCount 方法
// mapMutations 使用方式一
add() {
this.$store.commit('addCount')
},
// mapMutations 使用方式二
...mapMutations({
min: 'minCount'
}),
// 载荷传参 - 方式一:第二个参数
// amount() {
// this.$store.commit({
// type: 'amountCount',
// num: 10
// })
// },
// 载荷传参 - 方式二: 对象type方式
// amount() {
// this.$store.commit({
// type: 'amountCount',
// num: 10
// })
// },
// 载荷传参 - 方式三 该方式 amount方法会自动传参(在映射该方法时,传参过来,见模板的amount)
...mapMutations({
amount: 'amountCount'
}),
// actions 方式一
asyncHandler() {
this.$store.dispatch('asyncCount')
console.log('前面有异步,所以这行先执行');
},
// actions 方式二
// ...mapActions({
// asyncHandler: 'asyncCount'
// })
}
}
</script>
这篇博客介绍了如何在Vue2项目中使用Vuex3,包括安装vuex@3.4.0,将Vuex引入到main.js,并在src根目录下创建store文件夹及index.js文件,提供了一个简单的使用示例。
3万+

被折叠的 条评论
为什么被折叠?



