开发当中有这么一个场景,就是登录成功之后就把userInfo存到了Vuex当中,layout页面中的Home组件使用userInfo里的userType,使用方式是在data中定义一个变量userType,然后在created当中获取this.$store.state.userInfo.userType并赋值给data中的userType,但是出现了个问题,当我在兄弟组件(About)当中使用了仓库中的userType并修改了它时,我Home组件的userType并没有实时更新,具体原因如下:
以下四种方式都可以正常的使用到userType,但是使用第四种初始化赋值的时候发现userType失去了它的响应式(Vue2):
-
直接引用
<li>我是直接获取的userType:{{ $store.state.userInfo.userType }}</li>
-
mapState解构
import { mapState } from "vuex"; computed: { ...mapState(["userInfo"]), }
-
computed计算属性
computed: { userType() { return this.$store.state.userInfo.userType; } },
-
初始化赋值
created() { this.userType = this.$store.state.userInfo.userType; }
效果:
原因的话也很简单:
第一种方式直接引用$store.state.userInfo.userType是直接访问了userInfo对象的userType属性,这种方式会保持响应式,因为在Vue初始化时会将userInfo对象转为响应式对象。
第二种方式使用了mapState解构,它会将userInfo对象映射为当前组件的计算属性,这样就可以直接使用this.userInfo.userType来访问userType属性,这种方式也会保持响应式。
第三种方式使用了计算属性userType,每当this.$store.state.userInfo.userType发生变化时,计算属性会重新计算并返回新的值,这种方式也会保持响应式。
第四种方式在created钩子中直接将this.$store.state.userInfo.userType赋值给了this.userType,但是这种方式是普通赋值,没有经过Vue的响应式处理,所以this.userType不会保持响应式。
注:只是简单记录一下开发遇到的小问题,来加深自己的印象!