Vite + Vue3 + Pinia + es6 + TypeScript 搭建项目

vite 中文参考文档:https://vitejs.cn/guide/#scaffolding-your-first-vite-project

执行  npm init vite@latest

步骤如下图: 下载依赖 npm i 

启动项目: npm run dev

 

 

 

pinia文档:https://pinia.web3doc.top/

vuex4文档:https://vuex.vuejs.org/zh/installation.html

pinia和vuex的区别

pinia文档:https://pinia.web3doc.top/

vuex4文档:https://vuex.vuejs.org/zh/installation.html

区别:

  • mutations 不再存在

  • 无需创建自定义复杂包装器来支持 TypeScript,所有内容都是类型化的,并且 API 的设计方式尽可能利用 TS 类型推断

  • 不再需要注入、导入函数、调用函数、享受自动完成功能!

  • 无需动态添加 Store,默认情况下它们都是动态的,您甚至都不会注意到。请注意,您仍然可以随时手动使用 Store 进行注册,但因为它是自动的,您无需担心。

  • 不再有 modules 的嵌套结构。您仍然可以通过在另一个 Store 中导入和 使用 来隐式嵌套 Store,但 Pinia 通过设计提供平面结构,同时仍然支持 Store 之间的交叉组合方式。 您甚至可以拥有 Store 的循环依赖关系

  • 没有 命名空间模块。鉴于 Store 的扁平架构,“命名空间” Store 是其定义方式所固有的,您可以说所有 Store 都是命名空间的

pinia 数据持久化处理

pinia-plugin-persistedstate
or
pinia-plugin-persist

pinia-plugin-persistedstate文档:https://www.npmjs.com/package/pinia-persistedstate-plugin

pinia-plugin-persist文档:https://www.npmjs.com/package/pinia-plugin-persist

// main.ts 使用
const app = createApp(App);
app.use(createPinia());
// 组件内使用(导入即用)
<script setup lang="ts">
import { ref } from "vue";
import { useStore } from "@/store/index";

defineProps<{ msg: string }>();

const count = ref(0);
const store = useStore();
console.log(store, "store");
</script>

<template>
  <h1>{{ msg }}</h1>
  <div>{{ store.count }}</div>
</template>
// store/index.ts
import { defineStore } from "pinia";

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useStore = defineStore("main", {
  // other options...
  state: () => {
    return {
      count: 10,
    };
  },
  getters: {},
  actions: {},
});

// 注明使用vue-cli脚手架道理也是一样的不赘述了!!!
posted @ 2022-08-27 16:52  蓝色帅-橙子哥  阅读(584)  评论(0编辑  收藏  举报