Vuex 拾遗

引入Vuex的目的:为众多的Vue组件提供一个全局管理共享组件状态的控制中心,当一个共享状态改变时,能使调用该共享状态的组件得到更新。并且使用Vuex的API,每个共享状态的改变都能被追踪。

组件如何引入Vuex:

组件在实例化时,通过store选项引入Vuex的共享变量。之后组件通过this.$store.someprops.subprops访问共享变量

复制代码
Vuex 通过 store 选项,提供了一种机制将状态从根组件『注入』到每一个子组件中(需调用 Vue.use(Vuex)):

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
复制代码

组件的重构为使用Vuex的方式,需要作出的改变:

1、将组件从data获取数据的方式改为计算属性去处理。

1
2
3
4
5
computed:{
   shareData(){
       return this.$store.state.shareData 
    
}

 

Vuex 四大关键词:state,getters,mutations, actions

state:基本的共享状态定义,组件通过this.$score.state.props访问,有简化方法mapState;

getters:适用于对state进行计算,组件通过this.$score.getters.props访问,有简化方法mapGetters;

mutations:用来改变state的状态,由state.commit('mutationtype')调用,只能用同步方法,有简化方法mapMutations;

 actions:解决mutations不能用异步方法的缺陷,其提供了context参数,通过context.commit,context.dispatch触发mutations,或者通过 context.state 和 context.getters 来获取 state 和 getters,有简化方法mapActtions

备注:还有一个modules参数,支持将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

 

栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// make sure to call Vue.use(Vuex) if using a module system
 
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--
  }
})
 
new Vue({
  el: '#app',
  computed: {
    count () {
        return store.state.count
    }
  },
  methods: {
    increment () {
      store.commit('increment')
    },
    decrement () {
        store.commit('decrement')
    }
  }
})

  

 

posted @   yihailin  阅读(205)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示