Vue视图中导入Vuex mapState辅助函数时出现导入警告、运行报错问题
问题原因
- 报错本质是JS严格区分大小写的语法规则触发的:当前安装的vuex@3.4.0版本,对外导出的状态映射辅助函数为大写S开头的
mapState,代码中两处将函数名写为全小写的mapstate,模块解析流程找不到对应的导出成员,因此触发编译阶段的导出缺失警告。 - 浏览器端的运行时报错是连锁反应:导入的
mapstate实际取值为undefined,既无法通过ES模块的导出校验,也无法作为函数被调用,最终触发Object(...) is not a function的TypeError,导致组件无法正常挂载渲染。 - 当前使用的vue@2.6.12与vuex@3.4.0为官方适配的兼容版本组合,不存在版本不兼容导致的函数缺失问题,所有报错完全来自拼写时的大小写不匹配。
修正方法
- 调整导入语句的大小写匹配:将
<script>块内的import { mapstate } from 'vuex'修改为import { mapState } from 'vuex' - 同步修正computed属性中的函数调用大小写:将
...mapstate(['userProfile'])修改为...mapState(['userProfile'])
修正后的可运行组件代码
<template> <div>TODO Athlete Profile {{ userProfile }} <b-button class="btn btn-danger" v-on:click="logout()">Logout</b-button> </div> </template> <script> import { mapState } from 'vuex' export default { title: 'Profile', methods: { logout() { this.$store.dispatch('logout') } }, computed: { ...mapState(['userProfile']) } } </script>
修改完成后重启npm run serve开发服务,编译警告会自动消除,组件可正常读取Vuex中的userProfile状态完成渲染。
内容的提问来源于stack exchange,提问作者Jack Miller
相关产品推荐
相关产品推荐

