在main.ts中创建一个新的 store 实例
import { createStore } from 'vuex'
// 创建一个新的 store 实例
const store = createStore({
state () {
return {
username:'张三'
}
},
mutations: {
changeName(state:any, us:string) {
state.username=us;
}
}
})
const app = createApp(App)
//添加
app.use(store)
新建一个文件staore/index.js?
import {createStore} from 'vuex'
const store = createStore({
state () {
return {
username:'张三'
}
},
mutations: {
changeName(state, us) {
state.username=us;
}
}
})
export default store;
?在main.ts引用
import store from './store/index'
const app = createApp(App)
app.use(store)
<template>
<div>
<span>{{$store.state.username}}</span>
<el-button type="primary" @click="OnClickChangeName">改名</el-button>
</div>
</template>
<script lang="ts" setup>
import {useStore} from 'vuex'
import { onMounted } from 'vue';
const store = useStore();
onMounted(() => {
console.log(store.state.username);
});
const OnClickChangeName=()=>
{
store.commit('changeName','王五');
}
</script>