在Vuex中Mutations修改状态操作下详解


当前第2页 返回上一页

第一种传参的方式

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

29

30

<template>

 <p>

 <h3>-------------------这是mutations传参测试-------------------</h3>

 <p>

  {{this.$store.state.students}}//将已经有的学生渲染在这儿

  <p>

  <button @click="addstu">点击添加</button>//绑定添加事件

  </p>

 </p>

 </p>

</template>

 

<script>

export default {

 methods: {

  addstu () {

   const newstu = {

   id: 5,

   name: '张国荣',

   age: 44

   }//定死一个要添加的学生,这就是要传给mutations的参数

   this.$store.commit('addStudent', newstu)

   //调用commit方法,更新state的数据,

   //第一个参数是mutations里面的方法名,

   //第二个参数是传给mutaitons里面addstudent方法的一个参数,

   //也就是要新加入的学生

  }

 }

}

</script>

在vuex.store中接收这个参数

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

const store = new Vuex.Store({

// 定义的公共变量

  state: {

   count: 1,

   students: [

    {

     id: 1,

     name: 'dx',

     age: 18

    },

    {

     id: 2,

     name: 'yx',

     age: 18

    },

    {

     id: 3,

     name: 'ym',

     age: 32

    },

    {

     id: 4,

     name: '刘亦菲',

     age: 30

    }

   ]

  },

 // state中的变量只能在mutations中通过方法修改

  mutations: {

   changeCount: function (state) {

   state.count++

   console.log('改变了count')

   },

   addStudent (state, stu) {

   state.students.push(stu)

   }//通过这种方式,接收来自组件传过来的新加入的学生

  },

  actions: {

  },

  getters: {

  }

})

第二种传参的方式

组件向vuex传参

1

2

3

4

5

6

7

8

9

10

11

12

13

addstu () {

   const newstu = {

   id: 5,

   name: '张国荣',

   age: 44

   }

   this.$store.commit({

   type: 'addStudent',

   newstu: newstu

   })//原先是传入两个参数,现在直接传入一个对象

   //type就是需要调用的mutations里面的方法

   //newstu就是要求接收的对象,也就是新加入的学生

  }

vuex接收组件传参

1

2

3

4

5

mutations: {

   addStudent (state, playload) {

   state.students.push(playload.newstu)

   }

  },

需要注意的是,addstudent接收到的第二个参数是一个完整的对象,所以参数的使用略微有点不同

相关学习推荐:javascript视频教程

以上就是在Vuex中Mutations修改状态操作下详解的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

vuex是什么?

vuex中常用知识点(总结)

vuex刷新页面数据丢失怎么解决

vuex中mutations怎么理解?怎么用?

vuex有什么用?

vuex使用场景是什么

vuex的五个属性是什么

什么时候使用vuex

vuex中mutations修改状态操作下详解

vuex中映射的完整指南

更多相关阅读请进入《vuex》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...