Vuex3.0x的入门及实战
可以进入vuex官方文档学习
vuex官方中文文档
一、Vuex的安装与引入
使用CDN引入
<script src="/path/to/vuex.js"></script>
使用npm安装vuex(确认有没有安装node)
npm install vuex --save
然后在main.js中调用vuex组件
import Vue from 'vue'
import Vuex from 'vuex'
Vue use(Vuex)
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
vuex依赖于Promise,你可以通过CDN形式或者直接使用npm/yarn安装到全局
CDN方式
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
npm/yarn方式
npm install es6-promise --save # npm
yarn add es6-promise # Yarn
二、构建store.js
vuex中全局属性state存放在store.js中,vue组件通过读取state中存放的变量完成组件间的通信,当state中变量值发生改变是,相应的vue组件也会发生更新
在根目录下创建store.js文件
//导入Vue和Vuex
import Vue from 'vue'
import Vuex from 'vuex'
//使用Vuex
Vue.use(Vuex)
const store = new Vuex.Store({
//定义状态
state:{
//定义全局变量
count:0
},
//计算属性
getters:{
},
//修改状态事件,必须同步函数
mutations:{
},
//提交 mutation,可以异步操作
actions:{
},
//模块
modules:{
}
})
export default store
将vuex组件导入到组件中
<script>
import vuex from 'Vuex'
</script>
三、组件中访问定义在Vuex中全局变量
- 通过$store.state.变量名访问
<h3>此时的count值为:$store.state.count</h3>
- 通过映射为组件的计算属性访问
首先从vuex引入mapState方法
import { mapState } from 'vuex'
再映射为组件的计算属性
computed: {
...mapState(["count"]),
},
四、操作Vuex中的全局变量
组件不能通过store.state.变量名
直接修改变量的状态,vuex提供了mutaions
对象来定义一些函数进行对state
中变量的修改,然后组件通过store.commit(‘函数名’)
触发mutations
中的函数来修改全局变量的状态
store.js
mutations: {
//state作为第一个参数
add(state) {
state.count++
},
//step作为额外参数
addN(state, step) {
state.count += step
},
组件中
add() {
this.$store.commit("add");
},
addN() {
this.$store.commit("addN", 3);
},
四、异步操作全局变量
vuex提供了actions
对象来进行一些异步操作,action
中定义的函数中通过调用mutaions
中的函数来进行异步修改,然后组件中通过store.dispatch(‘函数名’)
来调用异步函数
store.js
//异步操作state中的变量
actions: {
// 接收context作为第一个参数
addAsync(context) {
setTimeout(() => {
//调用mutation中定义的函数来对state中定义的变量进行修改
context.commit('add')
}, 2000);
},
// step作为第二个形参接收组件中调用该action方法传过来的实参
addNAsync(context, step) {
setTimeout(() => {
//step作为实参传给mutation中的函数
context.commit('addN', step)
}, 2000);
},
}
组件中
addAsync() {
this.$store.dispatch("addAsync");
},
addNAsync() {
this.$store.dispatch("addNAsync", 3);
}
五、getters
vuex中定义了getters