vuex
很好的解决非父子通信的问题。
1.定义
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式( 数据、方法 )。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。 以前是把数据和方法定义在每个对应的页面中。但是现在我们可以很好的利用vuex和模块化把数据和方法放在一个公共的池子中。很好的管理你的数据 。
state
getters
mutations: commit
actions : diptach
modules
2.安装
npm i vuex -S
3.特点
1.vuex是响应式的状态管理模式,当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。 2.不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
4.引入
//7. vuex //7.1 安装下载 //npm i vuex import Vuex from 'vuex' //7.2 实例化vuex仓库 Vue.use( Vuex ) let store = new Vuex.Store({ state:{ //可以理解为我们.vue中的data(){ return {} } username:'zs' } }) new Vue({ //Vue实例中添加路由功能 router, store, //当我们把store挂载到Vue实例上,那么每一个组件实例上都可以继承 $store render: h => h(App), }).$mount('#app')
模块化
在src下创建store/index.js
5.使用
1.state选项
state单一状态树,存放状态数据,只有一个Object tree
-
mapState辅助函数
...mapState( ['username','age'] ), ...mapState( { //推荐的写法 uname:'username', uage:'age' } ),
2.mutations
作用: 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
{ mutations:{ //需要放函数方法:理解为vue中的methods //使用store对象上的commit( 函数名 ) //mutations中的函数的第1个参数永远是state对象 changeUserName(state,name){ // console.log( 'changeUser1234',a ) state.username = name } } } this.$store.commit('changeUserName','鲁班')
3.actions
作用: 1.用来提交mutations,及在actions中不能直接修改state状态数据 2.可以发起异步请求操作
-
mapActions辅助函数
{ actions:{ //想要为actions中的函数传递多个参数请以对象形式传递 getBanners(context,user){ //context === store 仓库对象 // console.log('获取banner轮播图',context) console.log('store中的getbanners') console.log(user) setTimeout(()=>{ let result = [ 22,33,44 ] context.commit( 'changeBanners',result ) //拿到数据触发mustaions中修改state变量的方法 },2000) } } } --------------------------------------------------------------------------------------------- methods:{ // getBanners(){ // console.log('我想拿banner数据') // }, ...mapActions(['getBanners']), fn(){ //console.log(this.$store,'fn') // $store.dispatch('actions中的某个函数') this.$store.dispatch('getBanners') } }
<button @click="$store.dispatch('getBanners')">执行actions下的方法1</button> <button @click="getBanners({ phone:'158xxxx',password:'12345' })">使用actioins的辅助函数</button>
4.getters
作用: 从store中的state中派生出一些其他状态,相当于computed 最终在.vue页面中直接访问getters就可以,不访问state
-
mapGetters辅助函数
{ getters:{ age(state){ return state.age + 1 } } } -------------------------------- { computed:{ ...mapGetters(['age']) }, } --------------------------------- {{ $store.getters.age }} <hr> {{age}}
6. 优化
7.modules
作用: 存放项目中的子模块 在每一个子模块中都有: state mutations actions getters
8. namespaced
namespaced在子模块中增加namespaced命名空间,可以解决命名冲突的问题