之前說過,對state的修改必須經過mutations,而mutations中是用來定義方法的,在vue文件中通過提交某個方法來完成state的修改,比如說現在點擊一個按鈕,讓counter+1,規范的做法如下:
vue文件:
<template> <div> <h1>我是首頁頁面</h1> <h2>{{$store.state.counter}}</h2> <button @click="addition">counter+1</button> </div> </template> methods: { addition(){ this.$store.commit('increment') } }
store下的index.js:
const store = new Vuex.Store({ state:{ counter: 1000 }, getters: {}, mutations: { increment(state){ state.counter++ } }, actions: {}, modules: {} })
要調用mutations中的方法,必須通過commit的方式來提交,參數是方法的名稱。還有一個注意點的是,mutations中的方法默認參數1是state對象,可拿到state中的變量