vue3.0 中使用vuex 和 vue-router4
目录结构:
|-- babel_webpack
|-- .gitignore
|-- index.html
|-- package.json
|-- vite.config.js
|-- public
| |-- favicon.ico
|-- src
|-- App.vue // 需要用到
|-- main.js // 需要用到
|-- assets
| |-- logo.png
|-- components
| |-- HelloWorld.vue
|-- router
| |-- index.js // 需要用到
|-- store
| |-- index.js // 需要用到
|-- views
|-- Home.vue // 需要用到
App.vue
<template>
<router-view />
</template>
main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
const app = createApp(App);
app.use(router);
app.use(store);
app.mount('#app');
router/index.js
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: () => import('../views/Home.vue') }
]
});
export default router;
store/index.js
import { createStore } from 'vuex';
export default createStore({
state: {
count: 0
},
mutations: {
getIncrement(state, val = 0) {
state.count += val
}
},
actions: {
actionsIncrement(content, val) {
content.commit('getIncrement', val)
}
}
})
views/Home.vue
<template>
<div>Home....</div>
<div>store:{{ $store.state.count }}</div>
<div>num:{{ num }}</div>
<br />
<button @click="mutationsAdd">mutations-加加</button>
<button @click="actionsAdd">actions-加加</button>
</template>
<script>
import { ref, reactive } from 'vue'
import { useStore } from "vuex";
export default {
setup() {
let num = reactive({
num: 0
})
const store = useStore(); // 使用useStore方法
function mutationsAdd() {
store.commit('getIncrement', 1000)
num.value = store.state.count;
console.log(num.value);
};
function actionsAdd() {
store.dispatch('actionsIncrement', '66')
num.value = store.state.count;
}
return { mutationsAdd, actionsAdd, num };
}
}
</script>
pages.json
{
"name": "03-vite",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"mddir": "^1.1.1",
"vue": "^3.0.5",
"vue-router": "^4.0.11",
"vuex": "^4.0.2"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.3.0",
"@vue/compiler-sfc": "^3.0.5",
"vite": "^2.4.4"
}
}
本文档展示了如何在Vue3.0项目中集成Vuex状态管理和Vue-Router4路由配置。通过创建App.vue、main.js、router/index.js和store/index.js文件,实现了基本的页面路由和状态存储。在Home.vue组件中,使用了Vuex的mutations和actions进行数据操作,并展示在页面上。项目结构清晰,适合初学者理解Vue3、Vuex和Vue-Router的协同工作。
8483

被折叠的 条评论
为什么被折叠?



