【摘自官网】Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。集中式存储管理应用的所有组件的状态。
核心概念:
每一个 Vuex 应用的核心就是 store(仓库),状态管理有5个核心:state,getter,mutation,action,module。
这篇文章整理记录一下,怎么使用store。
- 根目录 - 新建store目录 - 新建index.js文件
<!-- 页面路径:store/index.js --> import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex);//vue的插件机制 // Vuex.Store 构造器选项 const store = new Vuex.Store({ state:{ // 存放状态 "username":"foo", "age":18 } }) export default store
- 在 main.js 中导入文件
<!-- 页面路径:main.js --> import Vue from 'vue' import App from './App' import store from './store' Vue.prototype.$store = store // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 const app = new Vue({ store, ...App }) app.$mount()
State
- 页面获取state
1.通过属性访问,需要在根节点注入 store 。
2.在组件中使用,通过 this.$store 访问到 state 里的数据。<!-- 页面路径:pages/index/index.vue --> <template> <view> <text>用户名:{{username}}</text> </view> </template> <script> import store from '@/store/index.js';//需要引入store export default { data() { return {} }, computed: { username() { return store.state.username } } } </script>
3.通过 mapState 辅助函数获取。【一个组件需要获取多个状态的时候】<!-- 页面路径:pages/index/index.vue --> <template> <view> <text>用户名:{{username}}</text> </view> </template> <script> export default { data() { return {} }, computed: { username() { return this.$store.state.username } } } </script>
<!-- 页面路径:pages/index/index.vue --> <template> <view> <view>用户名:{{username}}</view> <view>年龄:{{age}}</view> </view> </template> <script> import { mapState } from 'vuex'//引入mapState export default { data() { return {} }, // 1. 从state中拿到数据 箭头函数可使代码更简练 // computed: mapState({ // username: state => state.username, // age: state => state.age, // }), // 2. 计算属性和子节点名称相同,可简写:username,age。 // computed: mapState([ // 'username', 'age' // ]) // 3. 为了能够使用 this 获取组件自己的data数据,必须使用常规函数。 // computed: { // ...mapState({ // username: function (state) { // return this.firstName + ' ' + state.username // }, // age: state => state.age, // }) // 4. 极大地简化写法,使用对象展开运算符将此对象混入到外部对象中 computed: { ...mapState({ username: state => state.username, age: state => state.age, }) }, } </script>