vuex-基础以及辅助函数的用法

3,653 阅读2分钟

1.vuex为什么会出现,解决了什么问题?

组件之间的参数传递有父子之间的传值,兄弟之间的传值,祖先和孙子之间的传值在层级较少的时候比较方便使用。 但是层级数较多,嵌套较麻烦时,使用起来就会相对的繁琐且不好维护 因此想到了vuex,将组件的共享状态抽取出来,以一个全局单例模式进行管理。组件树则形成了一个巨大的”视图“。 不管树的哪个位置,任何组件都能获取状态或者触发行为。

2.什么时候使用Vuex?

简单小型的项目没有必要使用,如果是中大型单页应用,便可以去使用。

3.Vuex的核心?

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)

特点: 1.Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

2.你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。

4.Vuex的基础用法?

建立store文件夹并创建index.js, 记得去main.js文件进行一下调用。大致index.js主要为(后面将会分部解析):
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
   state:{
       userName: 'phoebe',
       age: '23',
       habit: 'dance'
   },
   //主要是为了修改state
   mutations: {
       getUserName (state,value) {
           state.userName = value
       }
   },
   // action就是为了提交mutation
   actions: {
       getUserName (context,value) {
           context.commit('getUserName',value)
       }
   }
})

export default store
简单实现在store中存入一部分属性,然后部分组件去调用它。(单纯的取)
 //store/index.js
 state:{
        userName: 'phoebe',
        age: '23',
        habit: 'dance'
    }
        
  // app.vue
  
  // 1.简单获取
  this.$store.state.age
  this.$store.state.habit
  this.$store.state.userName
  
  //2.使用辅助函数 mapState
  import { mapState } from 'vuex'
  computed: {
      //this.habit :dance  即可调用
    ...mapState(['habit','age'.'userName'])
  },
修改state属性的几种方法?
1.commit mutations
  // store/index.js
    mutations: {
        getUserName (state,value) {
            state.userName = value
        }
    },
    
    // app.vue
    
    // 1.简单commit
    this.$store.commit('getUserName','phoebe')
    
    // 2.使用辅助函数 mapMutations将组件中的 methods 映射为 store.commit 调用
    import {mapMutations} from 'vuex'
    methods: {
      ...mapMutations(['getUserName']), 
      init () {
        //this.$store.state.userName:'change phoebe to MM' 即可改变
        this.getUserName('change phoebe to MM')  
      }
    }
2.使用action
 // store/index.js
   mutations: {
        getUserName (state,value) {
            state.userName = value
        }
    },
    // action就是为了提交mutation
    actions: {
        getUserName (context,value) {
            context.commit('getUserName',value)
        }
    }
    
    // app.vue
    
    //1. 简单分发
    this.$store.dispatch('getUserName', 'change name by action')
    
    //2.使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用
    import { mapActions} from 'vuex'
    methods: {
       ...mapActions(['getUserName']), 
    }
    init (){
      //this.$store.state.userName:'change phoebe to MA' 即可改变
      this.getUserName('change phoebe by MA') 
    }

先总结这些,后面持续再更~