vue3+vite+ts+vue-router+vuex搭建项目

vue3+vite+ts+vue-router+vuex搭建项目

      • 一.使用vite创建项目
      • 二.安装ts
      • 二.引入vue-router和vuex

一.使用vite创建项目

  1. npm install -g create-vite-app //安装全局create-vite-app
  2. create-vite-app vt
    //使用工具create-vite-app创建项目名为vt的vue3项目
  3. cd vt //进入项目文件夹
  4. npm install //初始化项目
  5. npm run dev //运行项目

二.安装ts

  1. npm安装typescript
//1. 安装ts
npm install -D typescript
  1. 在根目录建tsconfig.json文件
//tsconfig.json
{
 "compilerOptions": {
 	// TypeScript 默认会把代码编译为 ECMAScript 3
 	// esnext 表示仅仅校验转换 TypeScript 类型,不进行语法编译
 	"target": "esnext",
 	"module": "esnext",
 	// 开启严格模式,这使得对“this”的数据属性进行更严格的推断成为可能
 	"strict": true,
 	"jsx": "preserve",
 	"moduleResolution": "node"
 },// 配置需要校验的文件
 "include": [
 	"src/**/*.ts",
 	"src/**/*.vue"
 ],// 排除不需要 TypeScript 校验的文件
 "exclude": [
 	"node_modules"
 ]
}
  1. 修改src下的main.js 为main.ts
  2. 修改index.html里的main.js为main.ts
  3. 在 /src 目录下创建一个 .ts 文件,添加 .vue 文件的类型声明
   //main.d.ts
   // 在没用用到需要具体定义的内容的时候,可以只声明一下'*.vue'就可以
   // src/main.d.ts
   declare module '*.vue' {
    /* 
    import {ComponentOptions} from 'vue';
    const componentOptions: ComponentOptions;
    export default componentOptions; */
}

  1. 在 根目录下创建vue.config.js
   //vue.config.js
  module.exports = {
    publicPath: "/", 
    pages: {
        index: {
            entry: 'src/main.ts'
        }
    }
    pages: {
        index: {
            entry: 'src/main.ts'
        }
    }
}

二.引入vue-router和vuex

  1. npm安装typescript
npm install vue-router@4.0.0-beta.13
npm install vuex@4.0
  1. 在src目录下创建router文件夹 // 在router文件夹中新建index.ts
 //index.ts
 //现在创建router的方式与vue2.x的版本已经很不同了
import {createRouter, createWebHashHistory} from 'vue-router';
const routes = [
   {
       path: '/',
       redirect: '/home',
   },
   {
       path: '/home',
       component: () => import('../components/HelloWorld.vue')
   }
];

const router = createRouter({
   history: createWebHashHistory(), //替代之前的mode,是必须的
   routes
});
export default router;
  1. 修改app.vue
 //app.vue
<template>
<router-view></router-view>
</template>

<script>

export default {
 name: 'App'
}
</script>

  1. 创建src/store/index.ts,配置vuex
 //index.ts
import { createStore } from 'vuex'
export default createStore({
 state: {
   userInfo: {
     name:'yk'
   }
 },
 mutations: {
   getUserInfo (state, name) {
     state.userInfo.name = name
   }
 },
 actions: {
 },
 getters: {
 }
})
  1. 修改main.ts
 //main.ts
import {createApp} from 'vue';
import App from './App.vue';
import router from './router/index'; //引入vue-router
import store from './store/index'
import './index.css';

const app = createApp(App);
app.use(router); // 挂载到app上
app.use(store); // 挂载到app上
app.mount('#app');

你可能感兴趣的:(vue.js,前端,ts)