从零搭建vue3+vite+ts项目

1. 初始化项目

npm init vite@latest
Need to install the following packages:
  create-vite@latest
Ok to proceed? (y) y
√ Project name: ... my-vue3
√ Select a framework: » vue
√ Select a variant: » vue-ts

Scaffolding project in D:\Learning\todos-list...

Done. Now run:

  cd my-vue3
  npm install
  npm run dev

2.. 配置路由

npm i vue-router

src/route/index.ts(没有的直接创建对应文件夹和文件即可)

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

// 2. 配置路由
const routes: Array<RouteRecordRaw> = [
  {
    path: "/home", // 路由路径
    component: () => import("@/pages/home.vue"), // 对应组件
  },
];
// 1.返回一个 router 实列,为函数,里面有配置项(对象) history
const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 3导出路由   然后去 main.ts 注册 router.ts
export default router;

src/main.ts

import { createApp } from "vue";

import App from "./App.vue";
// 路由
import router from "@/router";

const app = createApp(App);
app.use(router).mount("#app");

ps:  引入的地方用@报错的同学 是因为别名没有配置(下图...为其他配置项)

{
  "compilerOptions": {
    ...
    "paths": {
      "@/*": ["src/*"],
    },
    ...
  }
}

3. 配置store

2.0 版本使用的市Vuex,3.0官网推荐使用pinia

npm i pinia

src/store/index.ts(同上面路由)

import { createPinia, defineStore } from "pinia";
const store = createPinia();

export const useStore = defineStore("storeId", {
  state: () => {
    return {},
  },
  actions: {},
  getters: {},
});

export { store };

可在state return出来的对象里自定义属性,Vuex中的mutation方法 在pinia中不再使用

src/main.ts

import { createApp } from "vue";

import App from "./App.vue";
// 路由
import router from "@/router";
// store
import { store } from "@/store";

const app = createApp(App);
app.use(router).use(store).mount("#app");

在对应页面或组件中使用store

<template>
  <div></div>
</template>

<script lang="ts" setup>
import { useStore } from "@/store";
const store = useStore(); // 后面可直接使用store.变量名
</script>

<style></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值