项目场景:
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
export default defineComponent({
name: 'Login.vue',
components: {},
setup () {
const onFormSubmit = (result: boolean) => {
if (result) {
console.log('result', result)
router.push('/')
const store = useStore()
store.commit('login')
console.log(store, useStore)
}
}
return {
onFormSubmit
}
}
})
</script>
vue3组合式api中使用store.commit报错,提示:
Uncaught runtime errors:
×
ERROR
Cannot read properties of undefined (reading 'commit')
TypeError: Cannot read properties of undefined (reading 'commit')
at onFormSubmit (webpack-internal:///./node_modules/ts-loader/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/views/Login.vue?vue&type=script&lang=ts:46:23)
at callWithErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:296:18)
at callWithAsyncErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:304:17)
at emit (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:800:5)
at Object.eval (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:7528:45)
at Proxy.submitForm (webpack-internal:///./node_modules/ts-loader/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/ValidateForm.vue?vue&type=script&lang=ts:19:21)
at eval (webpack-internal:///./node_modules/ts-loader/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[3]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/ValidateForm.vue?vue&type=template&id=36c7a62a&ts=true:24:60)
at eval (webpack-internal:///./node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js:1487:12)
at callWithErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:296:18)
at callWithAsyncErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:304:17)
打印store的值,显示undefined。
解决方法
经排查,const store = useStore()
不能写在setup函数的函数内部,应该就写在setup下。useStore这个方法的调用位置是有要求的,它只能在setup函数中调用,这是它的语法规定。文章来源:https://www.toymoban.com/news/detail-610039.html
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
const onFormSubmit = (result: boolean) => {
if (result) {
store.commit('login')
console.log(store, useStore)
}
}
return {
onFormSubmit
}
}
}
组合式API中使用vuex文档:官网文章来源地址https://www.toymoban.com/news/detail-610039.html
到了这里,关于【vue3+ts】TypeError: Cannot read properties of undefined (reading ‘commit‘)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!