上篇是讀取state,這篇是修改狀態。即如何操作Mutations。
一. $store.commit( )
Vuex提供了commit方法來修改狀態
1.store.js檔案
const mutations={ add(state){ state.count++ }, reduce(state){ state.count-- } }
2.在button上的修改方法
#
二. 傳值
#最簡單的修改狀態的操作,在實際專案中我們常常需要在修改狀態時傳值。例如上邊的例子,是我們每次只加1,而現在我們要透過所傳的值來相加。其實我們只要在Mutations再加上一個參數,並在commit的時候傳遞就可以了。我們來看具體程式碼:
1.store.js
const mutations={ add(state,n){ state.count+=n }, reduce(state){ state.count-- } }
2.修改按鈕的commit( )方法傳遞的參數,我們傳遞10,意思是每次加10.
#三.模板取得Mutations方法
在實際開發中我們也不喜歡看到$store.commit( )這樣的方法出現,我們希望跟呼叫範本裡的方法一樣呼叫。
例如:@click=”reduce” 就跟沒引用vuex外掛一樣。
1.在範本count.vue裡用import 引入我們的mapMutations:
import { mapState,mapMutations } from 'vuex'
#2 .在模板的
在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接收到的第二個參數是一個完整的對象,所以參數的使用略微有點不同
#相關學習推薦:javascript影片教學
以上是在Vuex中Mutations修改狀態操作下詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!