码迷,mamicode.com
首页 > 其他好文 > 详细

Vuex的使用总结

时间:2019-08-16 11:54:55      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:mamicode   规则   核心   代码   export   put   计算   rod   pre   

1、Vuex.store 的基本使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

Vuex 使用单一状态树,即用一个对象包含全部的应用层级状态,这也意味着,每个应用将仅仅包含一个 store 实例。

每一个 Vuex 应用的核心就是 store(仓库)。Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们更方便地使用一些工具比如 devtools 来调试我们的应用。

技术图片

1.1、创建 store

  • 首先安装 Vue、Vuex,在一个 JS 文件中创建一个 store
//store.js
import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    age () {
      return 232
    }
  },
  actions: {},
  mutations: {
    increment(state,) {
      state.count++;
    }
  }
})

export default store;
  • 然后在 main.js 中引入 store
// main.js
import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘
import store from ‘./store/store.js‘

Vue.config.productionTip = false

new Vue({
  el: ‘#app‘,
  router,
  store,
  components: { App },
  template: ‘<App/>‘
})

通过 store 选项能将状态从根组件“注入”到每一个子组件中(前面需先调用 Vue.use(Vuex))

在 main.js 文件中引入 store 后,该 store 实例会注入到根组件下的所有子组件中,其他组件就可以通过 this.$store 来访问这个 store 仓库了。

通过 this.$store.state 来访问数据、通过 this.$store.getters 来访问 getters 数据。

 

2、Vuex.Store 的选项

2.1、state 选项

在组件中使用 store 中的 state,我们可以直接通过 this.$store.state 来使用,也可以通过将状态返回到组件中的计算属性中来使用,而且每当 $store.state.count 变化的时候, 都会重新求取计算属性。

2.1.1、mapState() 函数

我们可以使用 mapState 辅助函数来帮助我们将 state 返回到组件的计算属性中,减少我们的代码量。

mapState(nameSpace, Array | Object),mapState 辅助函数的第一个参数可选,表示的是一个命名空间字符串(跟模块化有关),第二个参数可以是数组或者对象。函数最终返回一个对象,我们可以使用对象展开运算符将此对象插入到计算属性中。

import { mapState } from ‘vuex‘

<script>
export default {
  data () {
    return {}
  },
  computed: {
     name () { return ‘wen‘ },

     ...mapState([
        ‘count‘ // 组件中的 this.count 则是 this.$store.state.count
     ])
  }
}
</script>

// 或者使用对象作为参数
computed: {
    ...mapState({
      count: state => state.count,

      // 传字符串参数 ‘count‘ 等同于 `state => state.count`
      countAlias: ‘count‘,

      // 为了能够使用 `this` 获取局部状态,必须使用常规函数
      countPlusLocalState (state) {
        return state.count + this.localCount
      }
  })
}

 

2.2、getters 选项

store 中的 getters 就像计算属性一样,getters 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

Getter 接受 state 作为其第一个参数,Getter 也可以接受其他 getter 作为第二个参数。

const store = new Vuex.Store({
  state: {
    age: 23
  },
  getters: {
   //接收一个参数
    myAge: state => {
      return state.age + 2
    },
    //接收两个参数
    myAge2: (state, getters) => {
        return getters.myAge + 2;
    }
  }
})

在组件中可以通过 this.$store.getters 来访问 getters 中的数据。

你也可以通过让 getter 返回一个函数,来实现给 getter 传参。注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果

getters: {
  // 返回一个函数
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

//组件中访问时通过函数的形式访问,传入参数
this.$store.getters.getTodoById(2)

 

2.2.1、mapGetters() 函数

类似于 mapState 辅助函数一样,可以通过 mapGetters 辅助函数将 store 中的 getter 映射到局部计算属性

import { mapGetters } from ‘vuex‘

export default {
  computed: {
    // 数组作为参数
    ...mapGetters([
      ‘doneTodosCount‘,
      ‘anotherGetter‘,
      // ...
    ])
  }
}

//对象作为参数
...mapGetters({
  // 把 `this.doneCount` 映射为`this.$store.getters.doneTodosCount`
  doneCount: ‘doneTodosCount‘
})

 

2.3、mutations 选项

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

mutation 接受 state 作为第一个参数。

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

在组件中通过 this.$store.commit(‘increment‘) 的形式来调用 mutation 

mutation 可以接收其他数据作为其他参数,即载荷(payload)。一般来说,其他的参数可以作为对象传过去,这样更加简洁一点。

mutations: {
  increment (state, n) {
    state.count += n
  }
}
//调用时
this.$store.commit(‘increment‘, 10)

// payload 是对象
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
//调用时
store.commit(‘increment‘, {
  amount: 10
})
//或者此时可以使用对象风格进行提交
store.commit({
  type: ‘increment‘,
  amount: 10
})

 

2.3.2、mutation 往 state 的某个对象中添加属性

当 mutation 需要在 state 中的某个对象添加新属性时,不能直接添加,应该使用 Vue.set 方法,比如 Vue.set(obj, ‘newProp‘, 123) 。或者是新生成一个对象,用新对象替换旧对象:state.obj = { ...state.obj, newProp: 123 }

 

Vuex的使用总结

标签:mamicode   规则   核心   代码   export   put   计算   rod   pre   

原文地址:https://www.cnblogs.com/wenxuehai/p/11362855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!