1.store下的index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: { },
// 只有mutataions中定义的函数,才有权利修改state中的数据
mutations: {},
actions: {},
getters:{ },
})
export default store;
main.js中
import Vue from 'vue'
import App from './App.vue'
import store from './store/store';
// 1.引入vuex
import Vuex from 'vuex'
Vue.config.productionTip = false
Vue.use(Vuex);
new Vue({
// render渲染app根组件
render: h => h(App),
// 将创建的共享数据对象,挂载到Vue实例中,所以的组件,就可以从store中获取数据了
store: store,
}).$mount('#app')
2. state
state 提供唯一的数据资源,所有的共享的数据都要统一放到store 中的state中进行存储
2.1. 组件中访问state第一种方式:
this.$store.state.全局数据名称
组件访问vuex中的数据,模板中使用 $store
,script里面使this.$store.state
2.2 组件中访问state第二种方式:
- 从vuex中按需求导入mapState函数
import {mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
- 将全局数据,映射为当前组件的计算属性
computed :{ ...mapState(['count']) }
3.mutataions
mutation用于变更store中的数据
- 只能通过mutation更Store数据,不可以直接操作Store中的数据。
- 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
3.1触发mutations的第一种方式
this.$store.commit()
,
3.2 触发mutations
的第二种方式:通过以函数映射的方式
- 从vuex中按需求导入mapMutations函数
import { mapState, mapMutations } from 'vuex';
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性。
- 将指定的mutations函数,映射为当前组件的methods函数
methods: {
// 将全局的mutataions里面的sub函数,映射为当前组件的methods
...mapMutations(['sub']),
handleClick2() {
console.log("--");
this.sub();
}
},
4. actions
用于处理异步任务
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。
4.1触发actions的第一种方式
this.$store.dispatch
4.2 触发actions的第二 种方式:通过以函数映射的方式
1.从vuex中按需求导入mapState函数
import {maptActions} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
- 将指定的mutations函数,映射为当前组件的methods函数
methods:{
...maptActions(['addAsync'])
}
方式一:通过点击事件
方式二:直接使用映射的函数
<button @click="subAsync">-直接使用-Async</button>
5. getter
- Getter于对Store中的数据进行加工处理形成新的数据。他不会修改state中的原始数据起到的是包装数据的作用
- Getter 可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
- Store 中数据发生变化,Getter 的数据也会跟着变化。
5.1调用getters第一种方式
this.$store.getters.函数名字
<h3>{{ $store.getters.showNum }}</h3>
store下index.js中
getters:{
showNum (state){
return `当前最新的数据${state.count1}`
}
}
5.2 调用getters第二种方式
通过以函数映射的方式 1.从vuex中按需求导入mapState函数
import {maptGetters} from 'vuex'
- 通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
<h4>{{ showNum }}</h4>
computed :{ ...maptGetters(['showNum']) }
6.实践案例
基本效果
1. 创建项目,安装ant-desgin-vue,axios
npm install ant-desgin-vue@1.3.10
npm install axios
2. .prettierc
格式化工具的配置文件
3. 监听input输入框的变化
4. 新增列表数据
5.删除任务事项
6.监听复选框状态的改变
这里不使用剪头函数的话,拿不到参数。ant和elementui,必须通过箭头函数来传参