vue-vuex-mutations的基本使用


  之前說過,對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中的變量


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM