소스 검색

[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
Blake Newman 8 년 전
부모
커밋
9b6e452c47
7개의 변경된 파일24개의 추가작업 그리고 114개의 파일을 삭제
  1. 0 18
      docs/en/mutations.md
  2. 0 18
      docs/fr/mutations.md
  3. 1 19
      docs/ru/mutations.md
  4. 0 18
      docs/zh-cn/mutations.md
  5. 10 2
      src/index.js
  6. 10 36
      test/unit/test.js
  7. 3 3
      types/test/index.ts

+ 0 - 18
docs/en/mutations.md

@@ -75,24 +75,6 @@ mutations: {
 }
 ```
 
-### Silent Commit
-
-> Note: This is a feature that will likely be deprecated once we implement mutation filtering in the devtools.
-
-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:
-
-``` js
-store.commit('increment', {
-  amount: 1
-}, { silent: true })
-
-// with object-style commit
-store.commit({
-  type: 'increment',
-  amount: 1
-}, { silent: true })
-```
-
 ### Mutations Follow Vue's Reactivity Rules
 
 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:

+ 0 - 18
docs/fr/mutations.md

@@ -75,24 +75,6 @@ mutations: {
 }
 ```
 
-### Commit silencieux
-
-> Note : Cette fonctionnalité sera probablement dépréciée une fois que nous aurons implémenté le filtrage des mutations dans les devtools.
-
-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 :
-
-``` js
-store.commit('increment', {
-  amount: 1
-}, { silent: true })
-
-// with object-style dispatch
-store.commit({
-  type: 'increment',
-  amount: 1
-}, { silent: true })
-```
-
 ### Les mutations suivent les règles de réactivité de Vue
 
 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 :

+ 1 - 19
docs/ru/mutations.md

@@ -75,24 +75,6 @@ mutations: {
 }
 ```
 
-### Молчаливые мутации
-
-> Замечание: Эта возможность вероятно будет помечена как нерекоммендованная к использованию после появления функционала фильтрации мутаций в devtools.
-
-По умолчанию, каждая мутация попадает в плагины (например, в devtools). Иногда, впрочем, не хочется, чтобы плагины записывали каждое изменение состояния. Множественные мутации, происходящие в течении короткого периода времени не всегда необходимо отслеживать. В таких случаях существует возможность передать в `store.commit` третий параметр, чтобы "заставить замолчать" эту конкретную мутацию и сделать её невидимой в плагинах:
-
-``` js
-store.commit('increment', {
-  amount: 1
-}, { silent: true })
-
-// при использовании объектного синтаксиса
-store.commit({
-  type: 'increment',
-  amount: 1
-}, { silent: true })
-```
-
 ### Мутации следуют правилам реактивности Vue
 
 Поскольку состояние хранилища Vuex — это реактивная переменная Vue, при возникновении мутации зависящие от этого состояния компоненты Vue обновляются автоматически. Кроме того, это значит, что мутации Vuex имеют те же самые подводные камни, что и реактивность в обычном Vue:
@@ -183,4 +165,4 @@ store.commit('increment')
 // к этому моменту уже должны произойти.
 ```
 
-Для обработки асинхронных операций существуют [Действия](actions.md).
+Для обработки асинхронных операций существуют [Действия](actions.md).

+ 0 - 18
docs/zh-cn/mutations.md

@@ -75,24 +75,6 @@ mutations: {
 }
 ```
 
-### 静默提交
-
-> 注意:当我们在 devtools 中实现了 mutation 过滤功能后,此项功能将会被废弃。
-
-默认情况下,每个提交的 mutation 都会发送至插件(如 devtools)。但是在有些场景下,你可能不希望插件去记录每一个状态变更。在一个很短时间内向 store 的多个提交不总是需要被追踪的。在这种情况下,你可以向 `store.commit` 传第三个参数来对插件静默该 mutation:
-
-``` js
-store.commit('increment', {
-  amount: 1
-}, { silent: true })
-
-// 使用对象风格方式提交
-store.commit({
-  type: 'increment',
-  amount: 1
-}, { silent: true })
-```
-
 ### Mutations 需遵守 Vue 的响应规则
 
 既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:

+ 10 - 2
src/index.js

@@ -79,8 +79,16 @@ class Store {
         handler(payload)
       })
     })
-    if (!options || !options.silent) {
-      this._subscribers.forEach(sub => sub(mutation, this.state))
+    this._subscribers.forEach(sub => sub(mutation, this.state))
+
+    if (
+      process.env.NODE_ENV !== 'production' &&
+      options && options.hasOwnProperty('silent')
+    ) {
+      console.warn(
+        `[vuex] mutation type: ${type}. Silent option has been removed. ` +
+        'Use the filter functionality in the vue-devtools'
+      )
     }
   }
 

+ 10 - 36
test/unit/test.js

@@ -872,46 +872,20 @@ describe('Vuex', () => {
     expect(mutations[0].payload).toBe(2)
   })
 
-  it('plugins should ignore silent mutations', function () {
-    let initState
-    const mutations = []
+  it('should warn silent option depreciation', function () {
+    spyOn(console, 'warn')
+
     const store = new Vuex.Store({
-      state: {
-        a: 1
-      },
       mutations: {
-        [TEST] (state, { n }) {
-          state.a += n
-        }
+        [TEST] () {}
       },
-      plugins: [
-        store => {
-          initState = store.state
-          store.subscribe((mut, state) => {
-            expect(state).toBe(store.state)
-            mutations.push(mut)
-          })
-        }
-      ]
-    })
-    expect(initState).toBe(store.state)
-    store.commit(TEST, { n: 1 })
-    store.commit({
-      type: TEST,
-      n: 2
     })
-    store.commit(TEST, { n: 3 }, { silent: true })
-    store.commit({
-      type: TEST,
-      n: 4
-    }, {
-      silent: true
-    })
-    expect(mutations.length).toBe(2)
-    expect(mutations[0].type).toBe(TEST)
-    expect(mutations[1].type).toBe(TEST)
-    expect(mutations[0].payload.n).toBe(1) // normal commit
-    expect(mutations[1].payload.n).toBe(2) // object commit
+    store.commit(TEST, {}, { silent: true });
+
+    expect(console.warn).toHaveBeenCalledWith(
+      `[vuex] mutation type: ${TEST}. Silent option has been removed. ` +
+      'Use the filter functionality in the vue-devtools'
+    )
   })
 
   it('strict mode: warn mutations outside of handlers', function () {

+ 3 - 3
types/test/index.ts

@@ -20,11 +20,11 @@ namespace StoreInstance {
     amount: 1
   }).then(() => {});
 
-  store.commit("foo", { amount: 1 }, { silent: true });
+  store.commit("foo", { amount: 1 });
   store.commit({
     type: "foo",
     amount: 1
-  }, { silent: true });
+  });
 
   store.watch(state => state.value, value => {
     value = value + 1;
@@ -55,7 +55,7 @@ namespace RootModule {
         state.value;
         getters.count;
         dispatch("bar", {});
-        commit("bar", {}, { silent: true });
+        commit("bar", {});
       }
     },
     mutations: {