009 uni-app之vue、vuex
vue.js 视频教程
vue3.js 中文官网
vue.js 视频教程
vue语法:https://uniapp.dcloud.net.cn/tutorial/vue-vuex.html
vue2迁移到 vue3:https://uniapp.dcloud.net.cn/tutorial/migration-to-vue3.html
Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
状态管理有5个核心
每一个 Vuex 应用的核心就是 store(仓库),它包含着你的应用中大部分的状态 (state)。
状态管理有5个核心:state、getter、mutation、action、module。
mapState、mapGetters、mapMutations、mapActions
import
// 页面路径: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
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()
<!-- 页面路径:pages/index/index.vue -->
<template><view><text>用户名:{{username}}</text></view>
</template>
<script>import store from '@/store/index.js';//需要引入storeexport default {data() {return {}},computed: {username() {return store.state.username }}}
</script>
三种访问方式:
computed: {username() {return store.state.username }}
computed: {username() {return this.$store.state.username }}
computed: mapState({// 从state中拿到数据 箭头函数可使代码更简练username: state => state.username,age: state => state.age,})
Getter
getters: {doneTodos: state => {return state.todos.filter(todo => todo.done)}}
Mutation
- Vuex中store数据改变的唯一方法就是mutation
- Mutation 必须是同步函数
mutations: {add(state) {// 变更状态state.count += 2}}
methods: {addCount() {store.commit('add')}}
action
- action 提交的是 mutation,通过 mutation 来改变 state ,而不是直接变更状态。
- action 可以包含任意异步操作。
- action 可以执行任意的同步和异步操作
actions:{addCountAction (context) {context.commit('add')}}
分发 Action:
actions 通过 store.dispatch 方法触发。
methods: {add () {store.dispatch('addCountAction')}}
actions 支持以载荷形式分发:
actions:{addCountAction (context , payload) {context.commit('add',payload)}}
Module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
├── components # 组件文件夹└── myButton └── myButton.vue # myButton组件
├── pages└── index └── index.vue # index页面
├── static
├── store├── index.js # 我们组装模块并导出 store 的地方└── modules # 模块文件夹├── moduleA.js # 模块moduleA└── moduleB.js # 模块moduleB
├── App.vue
├── main.js
├── manifest.json
├── pages.json
└── uni.scss
// 页面路径:store/index.jsimport Vue from 'vue'import Vuex from 'vuex'import moduleA from '@/store/modules/moduleA'import moduleB from '@/store/modules/moduleB'Vue.use(Vuex)export default new Vuex.Store({modules:{moduleA,moduleB}})