vite项目 router使用 pinia使用
router使用
安装
yarn add vue-router || yarn i vue-router
yarn add vue-router || yarn i vue-router
在src内部创建 router文件夹(router.js, index.js)
main.js:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia } from 'pinia'
import router from './router'
createApp(App).use(router).mount('#app')
router.js:
const login = import(/* webpackChunkName: "loginjs" */"../views/login.vue")
let routes = [
{ path: "/", component: login },
{
path:'/home',
name:'home',
component:()=>import('../views/home.vue')
}
]
export default routes
index.js:
import routes from './router'
//createWebHistory路由模式路径不带#号:
//createWebHashHistory路由模式路径带#号:
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
app.vue
<div>
<router-view></router-view>
</div>
常用 跳转方法
//标签
<router-link to="login"> 去登陆</router-link>
//js
import { useRoute, useRouter } from 'vue-router';
const route = useRoute()
const router = useRouter()
//不传参
router.push('/login')
//传参
router.push({path:'/login',query:{id:1,type:2}})
//接受参数 route.query.xxx
alert('id === '+route.query.id)
pinia使用
安装
yarn add pinia
和
yarn add pinia-plugin-persist
yarn add pinia
yarn add pinia-plugin-persist
yarn add pinia-plugin-persist 数据持久化插件
main.js:
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPersist)
createApp(App).use(router).use(pinia).mount('#app')
tsconfig.json 在
compilerOptions
对象里加
"types": ["pinia-plugin-persist-uni"]
compilerOptions
"types": ["pinia-plugin-persist-uni"]
新建store文件夹 建index.js
import { defineStore } from 'pinia'
import Cookies from 'js-cookie'//如果需要存到cookie里面的话 需要 npm i js-cookie|| yarn add js-cookie
//存cookie方法
const cookiesStorage = {
setItem (key, state) {
return Cookies.set('info', state, { expires: 3 });
},
getItem (key) {
return Cookies.get('info')
},
}
// 定义并导出容器,第一个参数是容器id,必须唯一,用来将所有的容器
// 挂载到根容器上
export const userInfo = defineStore('user', {
// 定义state,用来存储状态的
state: () => {
return {
info: {
token: '',
userName: '',
userId: ''
},
}
},
//使用yarn add pinia-plugin-persist需要以下
persist: {
enabled: true, //开启存储
// storage:sessionStorage/localStorage,还可以自定义存入对应的如下
//不写以下也可以 默认是sessionStorage
strategies: [
{ storage: cookiesStorage, paths: ['info'] }
//{ storage: localStorage, paths: ['info'] }
//{ storage: sessionStorage, paths: ['info'] }
],
},
// 定义getters,类似于computed,具有缓存g功能
getters: {},
// 定义actions,类似于methods,用来修改state,做一些业务逻辑
actions: {}
})
存取数据
// 任意页面
import { userInfo } from '../store/index.js'
//存
import { ref, reactive, toRefs } from "vue";
let info = reactive({
token: "xxx123xxx456xxx789",
userId: "168",
userName: "张三",
});
useuserInfo.info = info
//取
console.log(useuserInfo.info)
版权声明:本文为weixin_54645059原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。