Vuex
(一)概述
vuex是一个专门为vue.js设计的集中式状态管理架构。
1、Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2、你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

(二)Vuex的安装
1、
- 在 Vue 之后引入 vuex 会进行自动安装
<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>
- NPM下载
npm install vuex --save
- Yarn下载
yarn add vuex
(三)简单使用Vuex
1、在src目录下新建一个store的文件夹,在下面建一个index.js的文件。
index.js
import Vue from 'vue'
import Vuex from 'vuex'
//1.安装插件
Vue.use(Vuex)
//2.创建对象
const store = new Vuex.Store({
state: {
counter: 10
},
mutations: {
decrement(state) {
state.counter--
},
}
})
//3.导出store独享
export default store
2、在main.js下进行引用
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
3、在app.vue中使用vuex
<template>
<div id="app">
<h2>----------APP---------</h2>
<h3>{{$store.state.counter}}</h3>
<button @click="decreate">-</button>
<router-view />
</div>
</template>
<script>
export default {
name: "App",
methods: {
decreate() {
this.$store.commit("decrement");
},
}
};
</script>
(四)State
1、概念
state中存放全局共享数据
2、访问
computed: {
count () {
return this.$store.state.全局数据名称
}
}
(五)Getter
1、概念
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数
2、使用
const store = new Vuex.Store({
state: {
counter: 1000,
students: [{
id: 110,
name: 'ewr',
age: 18
}, {
id: 210,
name: 'sdfsd',
age: 10
}, {
id: 120,
name: 'dfg',
age: 30
}, {
id: 113,
name: 'ghjg',
age: 24
}],
},
getters: {
powCounter(state) {
return state.counter * state.counter
},
morestu(state) {
return state.students.filter(s => {
return s.age >= 20;
});
},
}
})
(六)Mutation
1、概念
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
2、使用
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
3、访问
export default {
name: "App",
methods: {
increment() {
this.$store.commit("increment");
}
}
};
(七)Action
1、概念
Action 类似于 mutation,不同在于:
1)Action 提交的是 mutation,而不是直接变更状态。
2)Action 可以包含任意异步操作。
2、使用
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
3、访问
export default {
name: "App",
methods: {
increment() {
this.$store.dispatch("increment");
}
}
};
1348

被折叠的 条评论
为什么被折叠?



