store文件
import Vue from "vue";
import Vuex from "vuex"
Vue.use(Vuex)
let store = new Vuex.Store({
state: {
numbers: 0
},
// 只有 mutations 中定义的函数,才有权力修改 state 中的数据
mutations: {
// 改变化state中的值
add(state){
state.numbers ++
},
addN(state,step){
state.numbers += step
}
},
actions: {
// 执行异步操作 用 commit 调用 mutations 中的 add 方法
addAsync(context,step){
context.commit('addN',step)
}
},
modules: {}
})
export default store
man.js 全局注册
// 挂载store
import store from "@/store";
new Vue({
store,
router, render: h => h(App)
}).$mount('#app');
组件中引用 store
created() {
console.log(this.$store.state.numbers)
},
methods:{
handle(){
// commit 的作用是 调佣某个 mutation 函数
this.$store.commit('add')
// 这里的 dispatch 函数,专门用来触发 actions 函数
this.$store.dispatch('addAsync',6)
},
handleN(){
// commit 的作用是 调佣某个 mutation 函数
this.$store.commit('addN',3)
}
}
getter 使用
用于对 store 中的数据进行加工处理形成新的数据;
- getter 可以对 store 中已有的数据加工处理之后形成新的数据,类似 vue 的计算属性
- store 中数据发生变化,getter 的数据也会跟着变化
定义:
// 定义 getter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum(state){
return '当前最新的数量是 [ '+ state.count +' ]'
}
}
})
使用方法:
<h3>{{$store.getters.showNum}}</h3>
vuex 使用案例
store 方法
state: {
list: []
},
mutations: {
initList(state, list) {
state.list = list
}
},
actions: {
getList(context) {
axios.get('./newJson.json').then(res => {
context.commit('initList',res.data)
})
}
}
组件使用
<template>
<ul>
<li v-for='(item,index) in list' :key='index'><i>{{ item.id }}</i>{{ item.title }}</li>
</ul>
</template>
<script>
computed: {
// 将 store 中 list 数据映射出来,页面直接调用就行
...mapState(['list'])
},
created() {
this.$store.dispatch('getList')
}
</script>
json 数据 (newJson.json)
[
{
"id": 0,
"title": "你好"
},
{
"id": 1,
"title": "你好1"
}
]