当前位置:首页 » 《休闲阅读》 » 正文

vuex的五个属性及使用方法_JINGinC的博客

14 人参与  2022年02月01日 08:53  分类 : 《休闲阅读》  评论

点击全文阅读


vue内部数据流程图

 

 

 vue与组件之间的数据交互

 

 

 一.如何使用全局State?

//state的作用是存储公共数据
//state是响应式的,如果修改了属性,那么在相对应,组件视图上的值也会改变
//在store里定义格式
new Vuex.store({
  state: {
   属性名: 属性值 
  }
})

//在组件中使用格式
this.$store.state.属性名

//在模板中可省略this
{{$store.state.属性名}}

//在组件中使用map辅助函数:
computed: { 
  ...mapState(['属性名']), 
  ...mapState({'新名字': '属性名'})
}

如何使用modules中的state?

//使用在modules中的state
this.$store.state.moudules模块名.xxx

//使用map辅助函数:
computed: { 
  ...mapState('模块名', ['属性名']), 
  ...mapState('模块名', {'新名字': '属性名'})
}

二.如何使用全局getters?

//在store里定义getters
new Vuex.store({
  // 省略其他...
  getters: {
    // state 就是上边定义的公共数据state
    getter的名字1: function(state) {   //state 就是上边定义的公共数据state
      return 要返回的值
    }
  }
})

//在组件中使用:
this.$store.getters.getter的名字

//使用map辅助函数:
computed: { 
  ...mapGetters(['getters的名字']), 
  ...mapGetters({'新名字': 'getters的名字'})
}

如何使用modules中的getters?

//使用modules中的属性
{{$store.gerters.模块名.数据项名}}

//使用map辅助函数:
computed: { 
  ...mapGetters('模块名', ['数据项名']), 
  ...mapGetters('模块名',{'新名字': '数据项名'})
}

 三.如何使用全局mutations?

//在store里定义mutations
new Vue.store({
  // 省略其他...
  mutations:{
    // 每一项都是一个函数,可以声明两个形参
  	mutation名1:function(state [, 载荷]) {
  
    },
    mutation名2:function(state [, 载荷]) {
  
    },
	}
})

//在组件中使用:
this.$store.commit('mutation数据项名', 参数)   //这里的commit是固定的方法

//使用map辅助函数:
methods: { 
  ...mapMutations(['mutation数据项名']), 
  ...mapMutations({'新名字': 'mutation数据项名'})
}

如何使用modules中的mutations(namespaced:true)?

//使用modules中的属性
{{$store.commit('模块名/mutations数据项名',参数)}}

//使用map辅助函数:
methods: { 
  ...mapMutations('模块名', ['mutations数据项名']), 
  ...mapMutations('模块名',{'新名字': 'mutations数据项名'})
}

四.如何使用全局actions?

//在store里定义actions
new Vuex.store({
  // 省略其他...
  actions: {
    // context对象会自动传入,它与store实例具有相同的方法和属性
    action的名字: function(context, 载荷) {
      // 1. 发异步请求, 请求数据
      
      // 2. commit调用mutation来修改/保存数据
      
      // context.commit('mutation名', 载荷)
    }
  }
})

//在组件中使用
this.$store.dispatch('actions的名字', 参数)

//使用map辅助函数:
methods: { 
  ...mapActions(['actions的名字']), 
  ...mapActions({'新名字': 'actions的名字'})
}

如何使用modules中的actions(namespaced:true)? 

//使用modules中的属性:
{{$store.dispatch('模块名/actions数据项名',参数)}}


//使用map辅助函数:
methods: { 
  ...mapActions('模块名', ['actions数据项名']), 
  ...mapActions('模块名',{'新名字': 'actions数据项名'})
}


点击全文阅读


本文链接:http://zhangshiyu.com/post/34140.html

数据项  名字  属性  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1