上篇是讀取state,這篇是修改狀態(tài)。即如何操作Mutations。
一. $store.commit( )
Vuex提供了commit方法來修改狀態(tài)
1.store.js文件
const mutations={ add(state){ state.count++ }, reduce(state){ state.count-- } }
2.在button上的修改方法
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
二. 傳值
最簡單的修改狀態(tài)的操作,在實際項目中我們常常需要在修改狀態(tài)時傳值。比如上邊的例子,是我們每次只加1,而現(xiàn)在我們要通過所傳的值進行相加。其實我們只需要在Mutations里再加上一個參數(shù),并在commit的時候傳遞就就可以了。我們來看具體代碼:
1.store.js
const mutations={ add(state,n){ state.count+=n }, reduce(state){ state.count-- } }
2.修改按鈕的commit( )方法傳遞的參數(shù),我們傳遞10,意思就是每次加10.
<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
三.模板獲取Mutations方法
實際開發(fā)中我們也不喜歡看到$store.commit( )這樣的方法出現(xiàn),我們希望跟調用模板里的方法一樣調用。
例如:@click=”reduce” 就和沒引用vuex插件一樣。
1.在模板count.vue里用import 引入我們的mapMutations:
import { mapState,mapMutations } from 'vuex'
2.在模板的<script>標簽里添加methods屬性,并加入mapMutations
methods:mapMutations([ 'add','reduce' ]),
3.在模板中直接使用我們的reduce或者add方法
<button @click="reduce">-</button>
注意:封裝起來$store.commit
reduce: function () { this.$store.commit('add', 10) // html標簽是可以不寫this }
補充知識:vuex mutations參數(shù)傳遞
接下來做一個mutations的傳參講解
添加學生的例子
第一種傳參的方式
<template> <p> <h3>-------------------這是mutations傳參測試-------------------</h3> <p> {{this.$store.state.students}}//將已經(jīng)有的學生渲染在這兒 <p> <button @click="addstu">點擊添加</button>//綁定添加事件 </p> </p> </p> </template> <script> export default { methods: { addstu () { const newstu = { id: 5, name: '張國榮', age: 44 }//定死一個要添加的學生,這就是要傳給mutations的參數(shù) this.$store.commit('addStudent', newstu) //調用commit方法,更新state的數(shù)據(jù), //第一個參數(shù)是mutations里面的方法名, //第二個參數(shù)是傳給mutaitons里面addstudent方法的一個參數(shù), //也就是要新加入的學生 } } } </script>
在vuex.store中接收這個參數(shù)
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 })//原先是傳入兩個參數(shù),現(xiàn)在直接傳入一個對象 //type就是需要調用的mutations里面的方法 //newstu就是要求接收的對象,也就是新加入的學生 }
vuex接收組件傳參
mutations: { addStudent (state, playload) { state.students.push(playload.newstu) } },
需要注意的是,addstudent接收到的第二個參數(shù)是一個完整的對象,所以參數(shù)的使用略微有點不同
相關學習推薦:javascript視頻教程