在store文件夹下新建index.ts文件。
写下如下内容
import { createStore } from 'vuex'
export default createStore({
state: {
theme:true
},
mutations: {
changeTheme(state){
state.theme=!state.theme
}
},
actions: {
},
modules: {
}
})
在main.ts中引入store
import { createApp } from 'vue'
import App from './App.vue'
import 'virtual:windi.css'
import store from "./store/index"
createApp(App).use(store).mount('#app')
然后就能在组件中使用了。
在js模块中从store import
commit是提交一个方法。
<script setup lang='ts'>
import {ref} from "vue"
import store from "../../store/index"
function changeTheme(){
store.commit("changeTheme")
// console.log(store.commit())
}
</script>
<template>
<button @click="changeTheme" class="w-10 h-10">
<span v-if="1"></span>
<span v-if="!1"></span>
<span>{{store.state.theme}}</span>
</button>
</template>