SoFunction
Updated on 2025-03-02

vuex implementation calls the Mutations method like calling the template method

When we are writing vue projects, if we find that <button @click="$('jia')">-</button> in vuex is very troublesome, and we want to write it directly into jia in @click, how should we deal with it?

We can think about how we solved it when solving state, for this we will introduce the same solution as solving state

The first step is to introduce our mapMutations into our own templates

The code is as follows:

import {mapState,mapMutations} from 'vuex'

Note: We want to introduce mapMutations here, and the way you compare state is actually to introduce mapState

The second step is to add the methods attribute in the <script> tag of the template and add mapMutations

The code is as follows:

&lt;script&gt;

 import store from '@/store'

 import {mapState,mapMutations} from 'vuex'

 export default{

  data(){

   return{


   }

  },

computed:mapState(["num"]),

  methods:mapMutations([//Only follow this column
  

  'jia'

  

  ]),

  store

 }

&lt;/script&gt;

Step 3: Write directly into the template

&lt;template&gt;

 &lt;div&gt;

  &lt;h3&gt;{{num}}&lt;/h3&gt; 

&lt;button @click="jia"&gt;+&lt;/button&gt;&lt;!--Here--&gt; 

&lt;div&gt;

&lt;/template&gt;

Supplementary part: Code

import Vue from 'vue'

import Vuex from 'vuex'

(Vuex)

const state={//Status Object
num:0,

}

const mutations={//Triggered state
jian(state){

++

},

}

Test: Click the button button and it will always add

The above vuex implementation calls the Mutations method like calling the template method is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.