vuex mutations参数传递

vuex mutations参数传递接下来做一个 mutations 的传参讲解添加学生的例子 template div h3 这是 mutations 传参测试 h3 div this store state div div template

接下来做一个mutations的传参讲解

添加学生的例子

第一种传参的方式

<template> <div> <h3>-----------------------------------这是mutations传参测试--------------------------------</h3> <div> { 
   { 
   this.$store.state.students}}//将已经有的学生渲染在这儿 <div> <button @click="addstu">点击添加</button>//绑定添加事件 </div> </div> </div> </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中接收这个参数

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传参

addstu () { 
    const newstu = { 
    id: 5, name: '张国荣', age: 44 } this.$store.commit({ 
    type: 'addStudent', newstu: newstu })//原先是传入两个参数,现在直接传入一个对象 //type就是需要调用的mutations里面的方法 //newstu就是要求接收的对象,也就是新加入的学生 } 

vuex接收组件传参

mutations: { 
    addStudent (state, playload) { 
    state.students.push(playload.newstu) } }, 

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/219350.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午10:46
下一篇 2026年3月17日 下午10:46


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号