Skip to content

Commit fa9df67

Browse files
committed
[Patch] Remove silent option from mutations
- Now Dev tools supports filtering silent option is no longer required - Updated unit and type tests
1 parent dae2130 commit fa9df67

File tree

8 files changed

+12
-132
lines changed

8 files changed

+12
-132
lines changed

dist/vuex.js

+6-9
Original file line numberDiff line numberDiff line change
@@ -199,19 +199,18 @@ var Store = function Store (options) {
199199
var prototypeAccessors = { state: {} };
200200

201201
prototypeAccessors.state.get = function () {
202-
return this._vm.state
202+
return this._vm.$data.state
203203
};
204204

205205
prototypeAccessors.state.set = function (v) {
206206
assert(false, "Use store.replaceState() to explicit replace store state.")
207207
};
208208

209-
Store.prototype.commit = function commit (type, payload, options) {
209+
Store.prototype.commit = function commit (type, payload) {
210210
var this$1 = this;
211211

212212
// check object-style commit
213213
if (isObject(type) && type.type) {
214-
options = payload
215214
payload = type
216215
type = type.type
217216
}
@@ -226,9 +225,7 @@ Store.prototype.commit = function commit (type, payload, options) {
226225
handler(payload)
227226
})
228227
})
229-
if (!options || !options.silent) {
230-
this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); })
231-
}
228+
this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); })
232229
};
233230

234231
Store.prototype.dispatch = function dispatch (type, payload) {
@@ -289,9 +286,9 @@ Store.prototype.unregisterModule = function unregisterModule (path) {
289286

290287
if (typeof path === 'string') { path = [path] }
291288
assert(Array.isArray(path), "module path must be a string or an Array.")
292-
delete this._runtimeModules[path.join('.')]
293-
this._withCommit(function () {
294-
var parentState = getNestedState(this$1.state, path.slice(0, -1))
289+
delete this._runtimeModules[path.join('.')]
290+
this._withCommit(function () {
291+
var parentState = getNestedState(this$1.state, path.slice(0, -1))
295292
Vue.delete(parentState, path[path.length - 1])
296293
})
297294
resetStore(this)

docs/en/mutations.md

-18
Original file line numberDiff line numberDiff line change
@@ -75,24 +75,6 @@ mutations: {
7575
}
7676
```
7777

78-
### Silent Commit
79-
80-
> Note: This is a feature that will likely be deprecated once we implement mutation filtering in the devtools.
81-
82-
By default, every committed mutation is sent to plugins (e.g. the devtools). However in some scenarios you may not want the plugins to record every state change. Multiple commits to the store in a short period or polled do not always need to be tracked. In such cases you can pass a third argument to `store.commit` to "silence" that specific mutation from plugins:
83-
84-
``` js
85-
store.commit('increment', {
86-
amount: 1
87-
}, { silent: true })
88-
89-
// with object-style commit
90-
store.commit({
91-
type: 'increment',
92-
amount: 1
93-
}, { silent: true })
94-
```
95-
9678
### Mutations Follow Vue's Reactivity Rules
9779

9880
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:

docs/fr/mutations.md

-18
Original file line numberDiff line numberDiff line change
@@ -75,24 +75,6 @@ mutations: {
7575
}
7676
```
7777

78-
### Commit silencieux
79-
80-
> Note : Cette fonctionnalité sera probablement dépréciée une fois que nous aurons implémenté le filtrage des mutations dans les devtools.
81-
82-
Par défaut, chaque mutation committée est envoyée aux plugins (i.e. les devtools). Cependant dans certains scénarios vous pourriez ne pas vouloir que les plugins enregistrent chaque changement de state. Plusieurs commits dans le store en un court laps de temps n'ont pas toujours besoin d'être tracés. Dans ce genre de cas, vous pouvez passer un troisième argument à `store.commit` afin de rendre cette mutation silencieuse aux yeux des plugins :
83-
84-
``` js
85-
store.commit('increment', {
86-
amount: 1
87-
}, { silent: true })
88-
89-
// with object-style dispatch
90-
store.commit({
91-
type: 'increment',
92-
amount: 1
93-
}, { silent: true })
94-
```
95-
9678
### Les mutations suivent les règles de réactivité de Vue
9779

9880
Puisqu'un state de store de Vuex est rendu réactif par Vue, lorsque nous mutons le state, les composants Vue observant ce state seront automatiquement mis à jour. Cela signifie également que les mutations Vuex sont sujettes aux mêmes inconvénients que lorsqu'on travaille avec Vue :

docs/ru/mutations.md

+1-19
Original file line numberDiff line numberDiff line change
@@ -75,24 +75,6 @@ mutations: {
7575
}
7676
```
7777

78-
### Молчаливые мутации
79-
80-
> Замечание: Эта возможность вероятно будет помечена как нерекоммендованная к использованию после появления функционала фильтрации мутаций в devtools.
81-
82-
По умолчанию, каждая мутация попадает в плагины (например, в devtools). Иногда, впрочем, не хочется, чтобы плагины записывали каждое изменение состояния. Множественные мутации, происходящие в течении короткого периода времени не всегда необходимо отслеживать. В таких случаях существует возможность передать в `store.commit` третий параметр, чтобы "заставить замолчать" эту конкретную мутацию и сделать её невидимой в плагинах:
83-
84-
``` js
85-
store.commit('increment', {
86-
amount: 1
87-
}, { silent: true })
88-
89-
// при использовании объектного синтаксиса
90-
store.commit({
91-
type: 'increment',
92-
amount: 1
93-
}, { silent: true })
94-
```
95-
9678
### Мутации следуют правилам реактивности Vue
9779

9880
Поскольку состояние хранилища Vuex — это реактивная переменная Vue, при возникновении мутации зависящие от этого состояния компоненты Vue обновляются автоматически. Кроме того, это значит, что мутации Vuex имеют те же самые подводные камни, что и реактивность в обычном Vue:
@@ -183,4 +165,4 @@ store.commit('increment')
183165
// к этому моменту уже должны произойти.
184166
```
185167

186-
Для обработки асинхронных операций существуют [Действия](actions.md).
168+
Для обработки асинхронных операций существуют [Действия](actions.md).

docs/zh-cn/mutations.md

-18
Original file line numberDiff line numberDiff line change
@@ -75,24 +75,6 @@ mutations: {
7575
}
7676
```
7777

78-
### 静默提交
79-
80-
> 注意:当我们在 devtools 中实现了 mutation 过滤功能后,此项功能将会被废弃。
81-
82-
默认情况下,每个提交的 mutation 都会发送至插件(如 devtools)。但是在有些场景下,你可能不希望插件去记录每一个状态变更。在一个很短时间内向 store 的多个提交不总是需要被追踪的。在这种情况下,你可以向 `store.commit` 传第三个参数来对插件静默该 mutation:
83-
84-
``` js
85-
store.commit('increment', {
86-
amount: 1
87-
}, { silent: true })
88-
89-
// 使用对象风格方式提交
90-
store.commit({
91-
type: 'increment',
92-
amount: 1
93-
}, { silent: true })
94-
```
95-
9678
### Mutations 需遵守 Vue 的响应规则
9779

9880
既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:

src/index.js

+2-5
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,9 @@ class Store {
6060
assert(false, `Use store.replaceState() to explicit replace store state.`)
6161
}
6262

63-
commit (type, payload, options) {
63+
commit (type, payload) {
6464
// check object-style commit
6565
if (isObject(type) && type.type) {
66-
options = payload
6766
payload = type
6867
type = type.type
6968
}
@@ -78,9 +77,7 @@ class Store {
7877
handler(payload)
7978
})
8079
})
81-
if (!options || !options.silent) {
82-
this._subscribers.forEach(sub => sub(mutation, this.state))
83-
}
80+
this._subscribers.forEach(sub => sub(mutation, this.state))
8481
}
8582

8683
dispatch (type, payload) {

test/unit/test.js

-42
Original file line numberDiff line numberDiff line change
@@ -636,48 +636,6 @@ describe('Vuex', () => {
636636
expect(mutations[0].payload).toBe(2)
637637
})
638638

639-
it('plugins should ignore silent mutations', function () {
640-
let initState
641-
const mutations = []
642-
const store = new Vuex.Store({
643-
state: {
644-
a: 1
645-
},
646-
mutations: {
647-
[TEST] (state, { n }) {
648-
state.a += n
649-
}
650-
},
651-
plugins: [
652-
store => {
653-
initState = store.state
654-
store.subscribe((mut, state) => {
655-
expect(state).toBe(store.state)
656-
mutations.push(mut)
657-
})
658-
}
659-
]
660-
})
661-
expect(initState).toBe(store.state)
662-
store.commit(TEST, { n: 1 })
663-
store.commit({
664-
type: TEST,
665-
n: 2
666-
})
667-
store.commit(TEST, { n: 3 }, { silent: true })
668-
store.commit({
669-
type: TEST,
670-
n: 4
671-
}, {
672-
silent: true
673-
})
674-
expect(mutations.length).toBe(2)
675-
expect(mutations[0].type).toBe(TEST)
676-
expect(mutations[1].type).toBe(TEST)
677-
expect(mutations[0].payload.n).toBe(1) // normal commit
678-
expect(mutations[1].payload.n).toBe(2) // object commit
679-
})
680-
681639
it('strict mode: warn mutations outside of handlers', function () {
682640
const store = new Vuex.Store({
683641
state: {

types/test/index.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@ namespace StoreInstance {
2020
amount: 1
2121
}).then(() => {});
2222

23-
store.commit("foo", { amount: 1 }, { silent: true });
23+
store.commit("foo", { amount: 1 });
2424
store.commit({
2525
type: "foo",
2626
amount: 1
27-
}, { silent: true });
27+
});
2828

2929
store.watch(state => state.value, value => {
3030
value = value + 1;
@@ -55,7 +55,7 @@ namespace RootModule {
5555
state.value;
5656
getters.count;
5757
dispatch("bar", {});
58-
commit("bar", {}, { silent: true });
58+
commit("bar", {});
5959
}
6060
},
6161
mutations: {

0 commit comments

Comments
 (0)