安装vite
vite相当于vue-cli脚手架,因此应该首先安装它:
npm create vite@latest
然后按照提示选择选项完成创建
接着进入项目目录vite-project,并安装一下依赖:
cd vite-project
npm install
安装配置Vue-router@4
依然是在项目目录内:
npm install vue-router@4
然后创建router/router.js文件:
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = []
// 创建路由实例
const router = createRouter({
history: createWebHashHistory(),
routes //路由表
})
export default router
再回到main.js文件,引入带路由表的路由实例,并以插件形式使用:
import { createApp } from 'vue'
import App from './App.vue'
// 引入路由实例
import router from './router/router.js'
createApp(App).use(router).mount('#app')
配置页面
在src下创建目录pages,用于存放页面,并且在其中任意创建两个文件home.vue和About.vue
并且修改App.vue页面以供页面渲染:
<template>
<router-link to="/">首页</router-link> |
<router-link to="/about">关于</router-link>
<hr />
<router-view></router-view>
</template>
完善路由
//router/index.js
const routes = [
{ name: '首页', path: '/', component: () => import('../pages/Home.vue')},
{ name: '关于', path: '/about', component: () => import('../pages/About.vue')}
]
安装配置pinia
同样是在项目根目录:
npm install pinia
再创建pinia/pinia.js:
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
然后在main.js中引入,并以插件形式使用:
import { createApp } from 'vue'
import App from './App.vue'
// 引入路由实例
import router from './router/router.js'
// 引入pinia 实例
import pinia from './pinia/pinia.js'
createApp(App).use(pinia).use(router).mount('#app')
配置Store
创建pinia/store.js:
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
// other options...
state() {
return {
counter: 0
}
},
actions: {
increament() {
this.counter++
}
}
})
在About组件修改state数据,在Home组件显示state数据
修改一下Home组件:
<template>
首页-
{{ localStore.counter }}
</template>
<script setup>
// 导入Store
import { useStore } from "../pinia/store.js";
const localStore = useStore();
</script>
再修改一下About组件:
<template>
关于
<button @click="handler">修改state</button>
</template>
<script setup>
// 导入Store
import { useStore } from "../pinia/store.js";
const localStore = useStore();
function handler() {
localStore.increament();
}
</script>
本文暂时没有评论,来添加一个吧(●'◡'●)