Skip to content

Commit 9b6e452

Browse files
blake-newmanyyx990803
authored andcommitted
[Patch] Remove silent option from mutations (#457)
- Now Dev tools supports filtering silent option is no longer required - Added depreciation warning - Updated unit and type tests
1 parent aaaf599 commit 9b6e452

File tree

7 files changed

+24
-114
lines changed

7 files changed

+24
-114
lines changed

docs/en/mutations.md

Lines changed: 0 additions & 18 deletions
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

Lines changed: 0 additions & 18 deletions
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

Lines changed: 1 addition & 19 deletions
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

Lines changed: 0 additions & 18 deletions
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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,16 @@ class Store {
7979
handler(payload)
8080
})
8181
})
82-
if (!options || !options.silent) {
83-
this._subscribers.forEach(sub => sub(mutation, this.state))
82+
this._subscribers.forEach(sub => sub(mutation, this.state))
83+
84+
if (
85+
process.env.NODE_ENV !== 'production' &&
86+
options && options.hasOwnProperty('silent')
87+
) {
88+
console.warn(
89+
`[vuex] mutation type: ${type}. Silent option has been removed. ` +
90+
'Use the filter functionality in the vue-devtools'
91+
)
8492
}
8593
}
8694

test/unit/test.js

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -872,46 +872,20 @@ describe('Vuex', () => {
872872
expect(mutations[0].payload).toBe(2)
873873
})
874874

875-
it('plugins should ignore silent mutations', function () {
876-
let initState
877-
const mutations = []
875+
it('should warn silent option depreciation', function () {
876+
spyOn(console, 'warn')
877+
878878
const store = new Vuex.Store({
879-
state: {
880-
a: 1
881-
},
882879
mutations: {
883-
[TEST] (state, { n }) {
884-
state.a += n
885-
}
880+
[TEST] () {}
886881
},
887-
plugins: [
888-
store => {
889-
initState = store.state
890-
store.subscribe((mut, state) => {
891-
expect(state).toBe(store.state)
892-
mutations.push(mut)
893-
})
894-
}
895-
]
896-
})
897-
expect(initState).toBe(store.state)
898-
store.commit(TEST, { n: 1 })
899-
store.commit({
900-
type: TEST,
901-
n: 2
902882
})
903-
store.commit(TEST, { n: 3 }, { silent: true })
904-
store.commit({
905-
type: TEST,
906-
n: 4
907-
}, {
908-
silent: true
909-
})
910-
expect(mutations.length).toBe(2)
911-
expect(mutations[0].type).toBe(TEST)
912-
expect(mutations[1].type).toBe(TEST)
913-
expect(mutations[0].payload.n).toBe(1) // normal commit
914-
expect(mutations[1].payload.n).toBe(2) // object commit
883+
store.commit(TEST, {}, { silent: true });
884+
885+
expect(console.warn).toHaveBeenCalledWith(
886+
`[vuex] mutation type: ${TEST}. Silent option has been removed. ` +
887+
'Use the filter functionality in the vue-devtools'
888+
)
915889
})
916890

917891
it('strict mode: warn mutations outside of handlers', function () {

types/test/index.ts

Lines changed: 3 additions & 3 deletions
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)