在vuex中引入useStore函数,这个函数会返回一个store对象,就是index.js中createStore定义的对象
import { useStore } from 'vuex'
setup() { let store= useStore() console.log(store) let list=computed(()=>{ return store.state.list }) return { list }; },
<div>{{list}}</div>
Home.vue
<template> <div> <nav-header></nav-header> <nav-main></nav-main> <nav-footer></nav-footer> <div>{{ list }}</div> </div> </template> <script> import NavHeader from "@/components/navHeader/NavHeader.vue"; import NavMain from "@/components/navMain/NavMain.vue"; import NavFooter from "@/components/navFooter/NavFooter.vue"; import { defineComponent, ref, computed } from "vue"; import { useStore } from "vuex"; export default defineComponent({ name: "Home", props: {}, components: { NavHeader, NavMain, NavFooter, }, setup() { let store = useStore(); console.log(store); let list = computed(() => { return store.state.list; }); return { list, }; }, }); </script> <style></style>
这里需要注意一下
需要在全局挂载一下 否则会出现store=undefined的问题
main.js
import { createApp } from 'vue' import App from './App.vue' import store from './store' const app = createApp(App) app.use(store) app.mount("#app")
index.js
import { createStore } from 'vuex' export default createStore({ //定义所需要的状态的 state: { list:[ { title: "吃饭", complete: false, }, { title: "睡觉", complete: false, }, { title: "打豆豆", complete: true, }, ] }, mutations: { //添加任务 addTodo(state,payload){ state.list.push(payload) }, //删除任务 splice(下标,个数) delTodo(state,payload){ state.list.splice(payload,1) }, //清除已完成 clear(state,payload){ //把过滤之后的数组传进来 state.list=payload } }, actions: { }, //模块化 modules: { } })
这个时候
可以看到运行的结果