vuex的使用方法

快来打我* 2022-11-05 08:33 175阅读 0赞

npm install vuex -s
在src下创建store,文件夹下创建index.js

  1. import Vue from 'vue';
  2. import Vuex from 'vuex';
  3. Vue.use(Vuex);
  4. const store = new Vuex.Store({
  5. state:{
  6. count: 0
  7. },
  8. getters:{
  9. },
  10. mutations:{
  11. increment (state) {
  12. state.count++
  13. },
  14. remove (state) {
  15. state.count--
  16. }
  17. //同步操作,写法:this.$store.commit('mutations方法名',值)
  18. },
  19. actions:{
  20. increment (context) {
  21. context.commit('increment')
  22. }
  23. //含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
  24. }
  25. });
  26. export default store;

在组件获取vuex的数据

  1. <template>
  2. <div class="hello">
  3. <h1>{
  4. { msg }}</h1>
  5. <h2>{
  6. {this.$store.state.count}}</h2>
  7. <h2>{
  8. {count1}}</h2>
  9. <div ref="getText">Add "scoped" attribute to limit CSS to this component only</div>
  10. <!-- <button @click="dome">获取ref属性</button> -->
  11. <button @click="increment">vuex加</button>
  12. <button @click="remove">vuex减</button>
  13. </div>
  14. </template>
  15. <script>
  16. import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
  17. export default {
  18. name: 'HelloWorld',
  19. data () {
  20. return {
  21. msg: 'Welcome to Your Vue.js App'
  22. }
  23. },
  24. computed:{
  25. ...mapState({
  26. count1: state=>state.count * 88
  27. }),
  28. // ...mapMutations([
  29. // 'increment',
  30. // 'remove'
  31. // ])
  32. },
  33. methods: {
  34. dome () {
  35. console.log(this.$refs.getText)
  36. /* eslint-disable */
  37. },
  38. ...mapMutations([ //this.$store.commit简写方法
  39. 'increment',
  40. 'remove'
  41. ]),
  42. ...mapActions([
  43. 'increment', // map `this.increment()` to `this.$store.dispatch('increment')`
  44. //含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
  45. ]),
  46. // increment() {
  47. // let n = 2;
  48. // this.$store.commit('increment',n)//同步操作,写法:this.$store.commit('mutations方法名',值)
  49. // console.log(this.$store.state.count,n)
  50. // },
  51. // remove () {
  52. // this.$store.commit('remove')//同步操作,写法:this.$store.commit('mutations方法名',值)
  53. // }
  54. }
  55. }
  56. </script>
  57. <style scoped>
  58. </style>

发表评论

表情:
评论列表 (有 0 条评论,175人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Vuex使用

    前言 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,本文示例是基于vue-cli4创建的vue2项目。 简

    相关 vuex使用

    VUE + vuex的使用总结如下(查阅资料): 写在前面 本文旨在通过一个简单的例子,练习vuex的几个常用方法,使初学者以最快的速度跑起来一个vue + vue

    相关 Vuex使用

    (。^。) 来扯一扯Vuex呗~ Vuex:是一个专为vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方