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