1.创建项目
1.全局安装yarn和vite:
npm i -g yarn vite
2.使用yarn创建项目,xxx是项目名称:
yarn create vite xxx
如图选择vue:
选择vue-ts:
3.进入项目目录:
cd xxx
4.安装router和vuex的包:
yarn add vue-router@next vuex@next
package文件如图:
2.配置route文件
1.创建目录如下:
src/router/index.ts、 src/store/index.ts(后边再用)
配置router/index.ts文件
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const routes:Array< RouteRecordRaw > = [] //路由写法与vue2版本一样,下边在补充
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
2.配置main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
在写路由之前先要配置一些东西让我们的页路径写起来更方便一些
3.配置vite.config.ts文件
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
// import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
// '@components': join(root, '/components'),
'@': path.resolve(__dirname, 'src') //在任何模块文件内部,可以使用__dirname变量获取当前模块文件所在目录的完整绝对路径。
}
},
})
这样我们就可以使用’@‘来代替路径,会简便很多,在router/index.ts里添加路由,如下:
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const routes:Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/index', //使用redirect重定向,默认系统显示的第一页
},
{
path: '/index',
component: () => import('@/components/HelloWorld.vue'),
meta: { title: '首页'}
},
{
path: '/line',
component: () => import('@/components/line.vue'),
meta: { title: '线条'}
},
{
path: '/lifangti',
component: () => import('@/components/lifangti.vue'),
meta: { title: '立方体'}
},
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
App.vue里如下:
<template>
<router-view></router-view>
</template>
3.配置vuex
1.store/index.ts
import { createStore } from 'vuex'
const state = {
}
const mutations = {
}
const getters = {
}
const actions = {
}
const modules = {
}
export default createStore({
state,
getters,
mutations,
actions,
modules
})
2.配置main.ts文件
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
4.运行项目
yarn dev
5.导入three.js
1.安装three.js包
运行命令npm install three 导入three.js的模块包,成功后在node_modules中查看
2.在需要的组件中导入包
import * as THREE from "three";
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js'
这里我在导入的时候产生报错:Could not find a declaration file for module 'three',
报错信息提示要使用命令npm i --save-dev @types/three 或者在xxx.d.ts 文件里添加
declare module 'three'
declare module 'three/examples/jsm/controls/OrbitControls.js'
在百度这个问题的时候,我发现其他作者用的文件名是类似于这样的
类似于这样的,而我自己的文件目录下只有env.d.ts
所以上边的两行代码我放到了env.d.ts里,
上述的两种方法我都试过,npm命令执行后代码行还是报错,所以我也使用了第二种方式,代码行报错没了,但是我在记录这个问题想要复现报错的时候,把evn.d.ts里的两行代码注释掉,导入three的代码页没有报错,这让我有一些疑惑,开始记录这些问题的时候我还没有系统的学过vue3、ts、three,估计只能在学习的过程中去找这个原因了