Vuex的安装
使用
- 注册并导出
store.js
import Vue from 'vue'
// 1.导入vuex
import Vuex from 'vuex'
import 'es6-promise/auto'
// 2.注入
Vue.use(Vuex)
export default new Vuex.Store({
// 五大组件
state: {
count: 1,
msg: '学习vuex'
}
})
- 挂载
import store from '@/store'
// 挂载store
new Vue({
el: '#app',
render: h => h(App),
router,
store,
template: '<App/>',
components: { App }
})
在组件中引入state中的属性
使用computed单个引入
computed: {
count () {
return this.$store.state.count
}
}
映射简写
computed: {
// 仅当当前组件的计算属性方法和store中state中key是一样的使用
...mapState(['count'])
}
使用mapState多个引入
computed: mapState({
// 1.箭头函数
count: state => state.count,
// 2.传字符串参数 'count' 等同于state => state.count
countAlisa: 'count',
countLocal (state) {
return state.count + this.num
}
})
<h2>count值为 {{count}}</h2>
<h2>countAlias值为 {{countAlisa}}</h2>
<h2>countLocal值为 {{countLocal}}</h2>
使用对象的展开运算符多个引入
computed: {
...mapState({
countAlisa: 'count',
countLocal (state) {
return state.count + this.num
},
count: state => state.count,
})
}
使用getter获取属性
- 注册Getter
export default new Vuex.Store({
// 五大组件
state: {
count: 1,
msg: '学习vuex',
sites: [
{ id: 1, text: 'Runoob' },
{ id: 2, text: 'Google' },
{ id: 3, text: 'Taobao' }
]
},
getters: {
sites (state) {
console.log(state)
return state.sites
},
item: (state) => (i) => {
return state.sites[i]
}
}
})
- 组件中使用
获取整个数组对象
sites () {
return this.$store.getters.sites
},
获取数据中的某一项
item () {
return this.$store.getters.item(2)
}
使用mutation更新属性值
- 注册
mutations: {
addNum (state, num) {
state.count += num
},
// 不要再这里操作异步数据
addNumAsyn (state, payload) {
setTimeout(() => {
// 传入对象时,一般命名为payload
state.count += payload.num
}, 1000)
}
}
num为组件中传入的参数
- 使用
methods: {
addCount () {
// 不能这样操作,修改数据的唯一方法是修改mutation
// this.$store.state.count++
this.$store.commit('addNum', this.num)
},
addCountAsyn () {
this.$store.commit('addNumAsyn', {num: 5})
}
},
第一个参数是mutation中事件的名字,第二个参数是传递的数据
注意,在mutation中操作异步数据,页面上的数据显示正常,但实际state中的数据并没有发生变化,所有vuex建议不要再mutation中操作异步数据。
补充,第二种提交方式
addCount () {
// 第二种提交方式
this.$store.commit({
type: 'addNum',
num: 5
})
},
addNum (state, payload) {
state.count += payload.num
}
使用actions提交异步数据
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
- 在actions中注册
addNumAsynAciton ({commit}, payload) {
setTimeout(() => {
commit('addNumByAction', payload)
}, 1000)
},
2.在mutations中写提交函数
addNumByAction (state, payload) {
state.count += payload.num
},
3.在组件种使用
addCountAction () {
this.$store.dispatch('addNumAsynAciton', {num: 6})
}