Vuex中Mutations修改狀態是什么?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
上篇是讀取state,這篇是修改狀態。即如何操作Mutations。
一. $store.commit( )
Vuex提供了commit方法來修改狀態
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>
二. 傳值
最簡單的修改狀態的操作,在實際項目中我們常常需要在修改狀態時傳值。比如上邊的例子,是我們每次只加1,而現在我們要通過所傳的值進行相加。其實我們只需要在Mutations里再加上一個參數,并在commit的時候傳遞就就可以了。我們來看具體代碼:
1.store.js
const mutations={
add(state,n){
state.count+=n
},
reduce(state){
state.count--
}
}2.修改按鈕的commit( )方法傳遞的參數,我們傳遞10,意思就是每次加10.
<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
三.模板獲取Mutations方法
實際開發中我們也不喜歡看到$store.commit( )這樣的方法出現,我們希望跟調用模板里的方法一樣調用。
例如:@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參數傳遞
接下來做一個mutations的傳參講解
添加學生的例子
第一種傳參的方式
<template>
<p>
<h4>-------------------這是mutations傳參測試-------------------</h4>
<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中接收這個參數
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接收到的第二個參數是一個完整的對象,所以參數的使用略微有點不同
關于Vuex中Mutations修改狀態是什么問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。