第一次使用vuex
(1)创建项目,导入vscode
vue create lean-vuex
(2)关闭eslint(也可以不用,为了第一次便于理解)
创建vue.config.js
module.exports = {
lintOnSave: false
}
(3)运行项目
npm run serve
(4)查看官方文档
vuex3的文档
(5)安装依赖
npm i vuex@3.6.2
(6)写代码,创建store
import Vue from 'vue'
import App from './App.vue'
import Vue from 'vue'
import App from './App.vue'
//1.导入vuex的模块
import Vuex from 'vuex'
//2.注册vuex,注册组件...
Vue.use(Vuex)
//3.创建store
const store = new Vuex.Store({
state: {}//定义数据,类似于vue当中data
})
Vue.config.productionTip = false
new Vue({
//4.挂载store,会在组件this上面添加$xxx
store,
render: h => h(App),
}).$mount('#app')
(7)写代码,使用state,mutations,actions
<template>
<div id="app">
<!-- 使用state方式1-直接使用 -->
<div>count: {{$store.state.count}}</div>
<!-- 使用state方式2-自定义计算属性 -->
<div>count: {{count}}</div>
<div>username: {{username}}</div>
<!-- 调用mutations的方式1-直接调用 -->
<button @click="$store.commit('add')">+1</button>
<!-- 调用mutations的方式2-映射调用 -->
<button @click="add">+1</button>
<!-- mutations的传参 -->
<button @click="$store.commit('addN', 3)">+N</button>
<button @click="addN(3)">+1</button>
<!-- 调用actions的方式1-直接调用 -->
<button @click="$store.dispatch('addSync')">+1 async</button>
<!-- 调用mutations的方式2-映射调用 -->
<button @click="addSync">+1 async</button>
<!-- actions的传参 -->
<button @click="$store.dispatch('addNSync', 3)">+N async</button>
<button @click="addNSync(3)">+N async</button>
<!-- 使用getters的方式1-直接调用 -->
<div>{{$store.getters.showCount}}</div>
<!-- 使用getters的方式2-映射调用 -->
<div>{{showCount}}</div>
</div>
</template>
<script>
import {mapState, mapMutations,mapActions,mapGetters} from 'vuex'
export default {
name: 'App',
methods: {
//通过mapMutations批量生成方法
...mapMutations(['add','addN']),
//通过mapActions批量生成方法
...mapActions(['addSync','addNSync'])
},
computed: {
...mapGetters(['showCount']),
//通过mapState来批量生成计算属性
...mapState(['count', 'username'])
/*
count(){
return this.$store.state.count
},
username(){
return this.$store.state.username
}
*/
}
}
</script>
<style>
</style>