vuex useStore() 始终返回undefined

版本信息

  • "vue": "^3.0.0",
  • "vue-router": "^4.0.0-0",
  • "vuex": "^4.0.0-0"
  • "typescript": "~3.9.3"

问题描述

利用@vue/cli 创建的vue3+ts项目中, 调用 vuex 4提供的useStore()方法,始终返回undefined

这是我的代码

hook 定义
export interface IUseTodo {
    setTodo: (value: string) => void;
}

export function useTodo(): IUseTodo {
    const store: Store<any> = useStore();
    console.log("################",store)
    const setTodo = function (value: string) {
        const todo: ITodo = {
            id: new Date().getTime(),
            content: value,
            status: TODO_STATUS.DOING
        };
        store.dispatch(SET_TODO, todo);
    }
    return {
        setTodo
    }
}
使用hook
export default defineComponent({
  name: "TodoInput",
  components: {},
  setup() {
    const todoVal = ref("");
    const handleSetTodo = () => {
      if (!todoVal.value.trim().length) return;
      const { setTodo } = useTodo();
      setTodo("hello world");
      todoVal.value = "";
    };
    return {
      todoVal,
      handleSetTodo
    };
  }
});
阅读 14.4k
3 个回答

useStore()方法并不是在任何时机下都可以执行,需要保证useStore在setUp 执行时执行

你是不是少了从vuex中引入这个方法?

  import { useStore } from 'vuex'

考虑使用mixins试试,看你能不能接受,我也遇到了这个问题

export const useTodoMethod= {
    methods: {
        useTodo(): IUseTodo {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            //@ts-ignore
            return this.$store...;
        }
    }
};

export default defineComponent({
  mixins: [useTodoMethod], 
  ... 
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题