Vue。修改Vuex存储中的值时,将焦点放在组件的输入上

时间:2019-01-02 00:06:59

标签: javascript vue.js vuex

这是我组件中的代码:

//template
<v-select ref='ItemSearchSelect' :options="options"></v-select>
...
//script
created: function () {            
         this.$store.subscribe((setFocusSearch, state) => {
                if (setFocusSearch.type == 'setFocusSearch' && setFocusSearch.payload == true){
                    this.$refs.ItemSearchSelect.$refs.search.focus()
                    this.$store.commit('setFocusSearch',false)                    
                }
        })
    }, 

这是我的商店突变,可以从任何其他组件调用:

setFocusSearch(state,val){
      state.focussearch = val;
    },

有时它可以正常工作,但有时我可以在控制台中看到此错误,并且焦点无法正常工作

Uncaught TypeError: Cannot read property '$refs' of undefined
    at eval (ItemSearch.vue?d78c:38)
    at eval (vuex.esm.js?2f62:392)
    at Array.forEach (<anonymous>)
    at Store.commit (vuex.esm.js?2f62:392)
    at Store.boundCommit [as commit] (vuex.esm.js?2f62:335)
    at VueComponent.focusSearch (ShoppingCart.vue?0f5b:96)
    at keydown (eval at ./node_modules/cache-loader/dist/cjs.js?
    ...

在这种情况下总是会发生:

路由器将视图推送到包含我的ItemSearch组件和触发商店突变的组件的视图。目前,一切正常。现在,我将路由器推到另一个无关的视图,然后再将路由器推回到原始视图。这时,触发突变后,我得到了错误。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

当您的组件被卸载/销毁时,变异订阅将保留在商店中。这就是为什么您的订户中的this参考成为undefined的原因。

您需要做的是在销毁组件后删除订阅。参见https://vuex.vuejs.org/api/#subscribe ...

  

要停止订阅,请调用返回的退订函数。

例如

mounted () {
  // the name isn't really important and since this isn't a reactive property,
  // you don't need to have this defined in "data"
  this.focusSearchUnsubscriber = this.$store.subscribe(...)
},
beforeDestroy () {
  this.focusSearchUnsubscriber() // call the unsubscribe function
}

您会注意到我也使用了mounted而不是created。这是因为您的$refs直到您的组件被安装后才会被填充,因此使用更高版本的生命周期挂钩会增加一点安全性。