123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607 |
- <!DOCTYPE HTML>
- <html lang="en" >
- <head>
- <meta charset="UTF-8">
- <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
- <title>Mutations · Vuex</title>
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="description" content="">
- <meta name="generator" content="GitBook 3.2.2">
-
-
-
-
- <link rel="stylesheet" href="../gitbook/style.css">
-
-
-
- <link rel="stylesheet" href="../gitbook/gitbook-plugin-prism/prism.css">
-
-
-
- <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
-
-
-
- <link rel="stylesheet" href="../gitbook/gitbook-plugin-theme-vuejs/vue.css">
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- <meta name="HandheldFriendly" content="true"/>
- <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
- <meta name="apple-mobile-web-app-capable" content="yes">
- <meta name="apple-mobile-web-app-status-bar-style" content="black">
- <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
- <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
-
- <link rel="next" href="actions.html" />
-
-
- <link rel="prev" href="getters.html" />
-
- </head>
- <body>
-
- <div class="book">
- <div class="book-summary">
-
-
- <div id="book-search-input" role="search">
- <input type="text" placeholder="Type to search" />
- </div>
-
- <nav role="navigation">
-
- <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=vuejs" id="_carbonads_js"></script>
- <ul class="summary">
-
-
-
-
-
-
-
- <li class="chapter " data-level="1.1" data-path="./">
-
- <a href="./">
-
-
- Introduction
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.2" >
-
- <a target="_blank" href="https://github.com/vuejs/vuex/releases">
-
-
- Release Notes
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.3" data-path="installation.html">
-
- <a href="installation.html">
-
-
- Installation
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.4" data-path="intro.html">
-
- <a href="intro.html">
-
-
- What is Vuex?
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.5" data-path="getting-started.html">
-
- <a href="getting-started.html">
-
-
- Getting Started
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.6" data-path="core-concepts.html">
-
- <a href="core-concepts.html">
-
-
- Core Concepts
-
- </a>
-
-
- <ul class="articles">
-
-
- <li class="chapter " data-level="1.6.1" data-path="state.html">
-
- <a href="state.html">
-
-
- State
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.6.2" data-path="getters.html">
-
- <a href="getters.html">
-
-
- Getters
-
- </a>
-
-
- </li>
-
- <li class="chapter active" data-level="1.6.3" data-path="mutations.html">
-
- <a href="mutations.html">
-
-
- Mutations
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.6.4" data-path="actions.html">
-
- <a href="actions.html">
-
-
- Actions
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.6.5" data-path="modules.html">
-
- <a href="modules.html">
-
-
- Modules
-
- </a>
-
-
- </li>
-
- </ul>
-
- </li>
-
- <li class="chapter " data-level="1.7" data-path="structure.html">
-
- <a href="structure.html">
-
-
- Application Structure
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.8" data-path="plugins.html">
-
- <a href="plugins.html">
-
-
- Plugins
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.9" data-path="strict.html">
-
- <a href="strict.html">
-
-
- Strict Mode
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.10" data-path="forms.html">
-
- <a href="forms.html">
-
-
- Form Handling
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.11" data-path="testing.html">
-
- <a href="testing.html">
-
-
- Testing
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.12" data-path="hot-reload.html">
-
- <a href="hot-reload.html">
-
-
- Hot Reloading
-
- </a>
-
-
- </li>
-
- <li class="chapter " data-level="1.13" data-path="api.html">
-
- <a href="api.html">
-
-
- API Reference
-
- </a>
-
-
- </li>
-
-
- <li class="divider"></li>
- <li>
- <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
- Published with GitBook
- </a>
- </li>
- </ul>
- </nav>
-
-
- </div>
- <div class="book-body">
-
- <div class="body-inner">
-
-
-
- <div class="book-header" role="navigation">
-
- <!-- Title -->
- <h1>
- <i class="fa fa-circle-o-notch fa-spin"></i>
- <a href="." >Mutations</a>
- </h1>
- </div>
- <div class="page-wrapper" tabindex="-1" role="main">
- <div class="page-inner">
-
- <div id="book-search-results">
- <div class="search-noresults">
-
- <section class="normal markdown-section">
-
- <h1 id="mutations">Mutations</h1>
- <p>The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string <strong>type</strong> and a <strong>handler</strong>. The handler function is where we perform actual state modifications, and it will receive the state as the first argument:</p>
- <pre class="language-"><code class="lang-js"><span class="token keyword">const</span> store <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
- state<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- count<span class="token punctuation">:</span> <span class="token number">1</span>
- <span class="token punctuation">}</span><span class="token punctuation">,</span>
- mutations<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- increment <span class="token punctuation">(</span>state<span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token comment" spellcheck="true">// mutate state</span>
- state<span class="token punctuation">.</span>count<span class="token operator">++</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span><span class="token punctuation">)</span>
- </code></pre>
- <p>You cannot directly call a mutation handler. Think of it more like event registration: "When a mutation with type <code>increment</code> is triggered, call this handler." To invoke a mutation handler, you need to call <code>store.commit</code> with its type:</p>
- <pre class="language-"><code class="lang-js">store<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">'increment'</span><span class="token punctuation">)</span>
- </code></pre>
- <h3 id="commit-with-payload">Commit with Payload</h3>
- <p>You can pass an additional argument to <code>store.commit</code>, which is called the <strong>payload</strong> for the mutation:</p>
- <pre class="language-"><code class="lang-js"><span class="token comment" spellcheck="true">// ...</span>
- mutations<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- increment <span class="token punctuation">(</span>state<span class="token punctuation">,</span> n<span class="token punctuation">)</span> <span class="token punctuation">{</span>
- state<span class="token punctuation">.</span>count <span class="token operator">+</span><span class="token operator">=</span> n
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre>
- <pre class="language-"><code class="lang-js">store<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">'increment'</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span>
- </code></pre>
- <p>In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive:</p>
- <pre class="language-"><code class="lang-js"><span class="token comment" spellcheck="true">// ...</span>
- mutations<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- increment <span class="token punctuation">(</span>state<span class="token punctuation">,</span> payload<span class="token punctuation">)</span> <span class="token punctuation">{</span>
- state<span class="token punctuation">.</span>count <span class="token operator">+</span><span class="token operator">=</span> payload<span class="token punctuation">.</span>amount
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre>
- <pre class="language-"><code class="lang-js">store<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">'increment'</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
- amount<span class="token punctuation">:</span> <span class="token number">10</span>
- <span class="token punctuation">}</span><span class="token punctuation">)</span>
- </code></pre>
- <h3 id="object-style-commit">Object-Style Commit</h3>
- <p>An alternative way to commit a mutation is by directly using an object that has a <code>type</code> property:</p>
- <pre class="language-"><code class="lang-js">store<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
- type<span class="token punctuation">:</span> <span class="token string">'increment'</span><span class="token punctuation">,</span>
- amount<span class="token punctuation">:</span> <span class="token number">10</span>
- <span class="token punctuation">}</span><span class="token punctuation">)</span>
- </code></pre>
- <p>When using object-style commit, the entire object will be passed as the payload to mutation handlers, so the handler remains the same:</p>
- <pre class="language-"><code class="lang-js">mutations<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- increment <span class="token punctuation">(</span>state<span class="token punctuation">,</span> payload<span class="token punctuation">)</span> <span class="token punctuation">{</span>
- state<span class="token punctuation">.</span>count <span class="token operator">+</span><span class="token operator">=</span> payload<span class="token punctuation">.</span>amount
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre>
- <h3 id="mutations-follow-vues-reactivity-rules">Mutations Follow Vue's Reactivity Rules</h3>
- <p>Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue:</p>
- <ol>
- <li><p>Prefer initializing your store's initial state with all desired fields upfront.</p>
- </li>
- <li><p>When adding new properties to an Object, you should either:</p>
- <ul>
- <li><p>Use <code>Vue.set(obj, 'newProp', 123)</code>, or</p>
- </li>
- <li><p>Replace that Object with a fresh one. For example, using the stage-3 <a href="https://github.com/sebmarkbage/ecmascript-rest-spread" target="_blank">object spread syntax</a> we can write it like this:</p>
- <pre class="language-"><code class="lang-js">state<span class="token punctuation">.</span>obj <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token operator">...</span>state<span class="token punctuation">.</span>obj<span class="token punctuation">,</span> newProp<span class="token punctuation">:</span> <span class="token number">123</span> <span class="token punctuation">}</span>
- </code></pre>
- </li>
- </ul>
- </li>
- </ol>
- <h3 id="using-constants-for-mutation-types">Using Constants for Mutation Types</h3>
- <p>It is a commonly seen pattern to use constants for mutation types in various Flux implementations. This allows the code to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application:</p>
- <pre class="language-"><code class="lang-js"><span class="token comment" spellcheck="true">// mutation-types.js</span>
- <span class="token keyword">export</span> <span class="token keyword">const</span> SOME_MUTATION <span class="token operator">=</span> <span class="token string">'SOME_MUTATION'</span>
- </code></pre>
- <pre class="language-"><code class="lang-js"><span class="token comment" spellcheck="true">// store.js</span>
- <span class="token keyword">import</span> Vuex <span class="token keyword">from</span> <span class="token string">'vuex'</span>
- <span class="token keyword">import</span> <span class="token punctuation">{</span> SOME_MUTATION <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'./mutation-types'</span>
- <span class="token keyword">const</span> store <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vuex<span class="token punctuation">.</span>Store</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
- state<span class="token punctuation">:</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
- mutations<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- <span class="token comment" spellcheck="true">// we can use the ES2015 computed property name feature</span>
- <span class="token comment" spellcheck="true">// to use a constant as the function name</span>
- <span class="token punctuation">[</span>SOME_MUTATION<span class="token punctuation">]</span> <span class="token punctuation">(</span>state<span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token comment" spellcheck="true">// mutate state</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span><span class="token punctuation">)</span>
- </code></pre>
- <p>Whether to use constants is largely a preference - it can be helpful in large projects with many developers, but it's totally optional if you don't like them.</p>
- <h3 id="mutations-must-be-synchronous">Mutations Must Be Synchronous</h3>
- <p>One important rule to remember is that <strong>mutation handler functions must be synchronous</strong>. Why? Consider the following example:</p>
- <pre class="language-"><code class="lang-js">mutations<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- someMutation <span class="token punctuation">(</span>state<span class="token punctuation">)</span> <span class="token punctuation">{</span>
- api<span class="token punctuation">.</span><span class="token function">callAsyncMethod</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">{</span>
- state<span class="token punctuation">.</span>count<span class="token operator">++</span>
- <span class="token punctuation">}</span><span class="token punctuation">)</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre>
- <p>Now imagine we are debugging the app and looking at the devtool's mutation logs. For every mutation logged, the devtool will need to capture a "before" and "after" snapshots of the state. However, the asynchronous callback inside the example mutation above makes that impossible: the callback is not called yet when the mutation is committed, and there's no way for the devtool to know when the callback will actually be called - any state mutation performed in the callback is essentially un-trackable!</p>
- <h3 id="committing-mutations-in-components">Committing Mutations in Components</h3>
- <p>You can commit mutations in components with <code>this.$store.commit('xxx')</code>, or use the <code>mapMutations</code> helper which maps component methods to <code>store.commit</code> calls (requires root <code>store</code> injection):</p>
- <pre class="language-"><code class="lang-js"><span class="token keyword">import</span> <span class="token punctuation">{</span> mapMutations <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vuex'</span>
- <span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token punctuation">{</span>
- <span class="token comment" spellcheck="true">// ...</span>
- methods<span class="token punctuation">:</span> <span class="token punctuation">{</span>
- <span class="token operator">...</span><span class="token function">mapMutations</span><span class="token punctuation">(</span><span class="token punctuation">[</span>
- <span class="token string">'increment'</span><span class="token punctuation">,</span> <span class="token comment" spellcheck="true">// map `this.increment()` to `this.$store.commit('increment')`</span>
- <span class="token comment" spellcheck="true">// `mapMutations` also supports payloads:</span>
- <span class="token string">'incrementBy'</span> <span class="token comment" spellcheck="true">// map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`</span>
- <span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token operator">...</span><span class="token function">mapMutations</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
- add<span class="token punctuation">:</span> <span class="token string">'increment'</span> <span class="token comment" spellcheck="true">// map `this.add()` to `this.$store.commit('increment')`</span>
- <span class="token punctuation">}</span><span class="token punctuation">)</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre>
- <h3 id="on-to-actions">On to Actions</h3>
- <p>Asynchronicity combined with state mutation can make your program very hard to reason about. For example, when you call two methods both with async callbacks that mutate the state, how do you know when they are called and which callback was called first? This is exactly why we want to separate the two concepts. In Vuex, <strong>mutations are synchronous transactions</strong>:</p>
- <pre class="language-"><code class="lang-js">store<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token string">'increment'</span><span class="token punctuation">)</span>
- <span class="token comment" spellcheck="true">// any state change that the "increment" mutation may cause</span>
- <span class="token comment" spellcheck="true">// should be done at this moment.</span>
- </code></pre>
- <p>To handle asynchronous operations, let's introduce <a href="actions.html">Actions</a>.</p>
-
- </section>
-
- </div>
- <div class="search-results">
- <div class="has-results">
-
- <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
- <ul class="search-results-list"></ul>
-
- </div>
- <div class="no-results">
-
- <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
-
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <script src="//m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
- <div class="bsa-cpc"></div>
- <script>
- (function(){
- if(typeof _bsa !== 'undefined' && _bsa) {
- _bsa.init('default', 'CKYD62QM', 'placement:vuejsorg', {
- target: '.bsa-cpc',
- align: 'horizontal',
- disable_css: 'true'
- });
- }
- })();
- </script>
- </div>
-
-
- <a href="getters.html" class="navigation navigation-prev " aria-label="Previous page: Getters">
- <i class="fa fa-angle-left"></i>
- </a>
-
-
- <a href="actions.html" class="navigation navigation-next " aria-label="Next page: Actions">
- <i class="fa fa-angle-right"></i>
- </a>
-
-
-
- </div>
- <script>
- var gitbook = gitbook || [];
- gitbook.push(function() {
- gitbook.page.hasChanged({"page":{"title":"Mutations","level":"1.6.3","depth":2,"next":{"title":"Actions","level":"1.6.4","depth":2,"path":"actions.md","ref":"actions.md","articles":[]},"previous":{"title":"Getters","level":"1.6.2","depth":2,"path":"getters.md","ref":"getters.md","articles":[]},"dir":"ltr"},"config":{"plugins":["edit-link","prism","-highlight","github","-highlight","github"],"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"edit-link":{"label":"Edit This Page","base":"https://github.com/vuejs/vuex/tree/dev/docs"},"github":{"url":"https://github.com/vuejs/vuex/"},"prism":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":false,"twitter":false,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"theme-vuejs":{},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"theme":"default","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"title":"Vuex","language":"en","links":{"sharing":{"facebook":false,"twitter":false}},"gitbook":"2.x.x"},"file":{"path":"mutations.md","mtime":"2018-04-20T00:44:03.852Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2018-04-20T00:47:55.633Z"},"basePath":".","book":{"language":"en"}});
- });
- </script>
- </div>
-
- <script src="../gitbook/gitbook.js"></script>
- <script src="../gitbook/theme.js"></script>
-
-
- <script src="../gitbook/gitbook-plugin-edit-link/plugin.js"></script>
-
-
-
- <script src="../gitbook/gitbook-plugin-github/plugin.js"></script>
-
-
-
- <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
-
-
-
- <script src="../gitbook/gitbook-plugin-search/search.js"></script>
-
-
-
- <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
-
-
-
- <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
-
-
-
- <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
-
-
- </body>
- </html>
|