PageFour.vue 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <template>
  2. <div>
  3. <h1>我是页面四</h1>
  4. <!-- 从 vuex 中获取 count 值 -->
  5. <!-- $store 是 vuex 实例 -->
  6. <!-- $store.state.定义的属性名 -->
  7. <h1>{{ x }},{{ y }},{{ z }},{{ count }}</h1>
  8. <h1>当前count值:{{ $store.state.count }}</h1>
  9. <h1>当前count值(简化):{{ countNum }}</h1>
  10. <!-- <h1>getter中的值:{{ $store.getters.getCount }}</h1> -->
  11. <h1>getter中的值(简化):{{ getCount }}</h1>
  12. <div>
  13. <button @click="changeCount">修改count</button>
  14. <button @click="asyncChangeCount">异步修改count</button>
  15. </div>
  16. </div>
  17. </template>
  18. <script>
  19. // mapState 这里边式全部的vuex 中的属性
  20. // mapMutations 这里边式全部的vuex 中的mutation方法
  21. // mapGetters 这里边式全部的vuex 中的getter属性
  22. import { mapState, mapMutations, mapGetters, mapActions } from 'vuex'
  23. export default{
  24. name:"PageFour",
  25. methods:{
  26. // 利用 mapMutations 方法 简化对 vuex 中 mutation 方法的调用
  27. // mapMutations 内部传递一个数组 数组中写入要引用的 vuex 中的 mutation 方法名
  28. ...mapMutations(["countAdd"]),
  29. ...mapActions(["actionFun"]),
  30. changeCount(){
  31. // 通过 commit 方法 调用 mutations 中的方法
  32. // 第一个参数 就是 mutations 中的方法名
  33. // 从第二个参数开始 就是 传递给 mutations 中的方法的参数
  34. // this.$store.commit("countAdd",10);
  35. this.countAdd(5);
  36. },
  37. asyncChangeCount(){
  38. // 调用 vuex 中的 action 方法 通过 dispatch 方法调用
  39. // this.$store.dispatch("actionFun",50);
  40. this.actionFun(50);
  41. }
  42. },
  43. created(){
  44. // 在js中引用vuex 中的值 前面需要添加this
  45. console.log(this.$store.state.count);
  46. },
  47. computed:{
  48. // 利用 mapState 方法 简化对 vuex 中值的引用
  49. // mapState 内部传递一个数组 数组中写入要引用的 vuex 中的属性名
  50. ...mapState(["count","x","y","z"]),
  51. // 利用 mapGetters 方法 简化对 vuex 中 getter 属性的调用
  52. // mapGetters 内部传递一个数组 数组中写入要引用的 vuex 中的 getter 属性名
  53. ...mapGetters(["getCount"]),
  54. countNum(){
  55. // 可以利用计算属性 简化对 vuex 中值的引用
  56. return this.$store.state.count;
  57. }
  58. }
  59. }
  60. </script>