Vue3 + vite2 + ts + elementPlus问题汇总

568 阅读1分钟

1.全局Loading、MessageBox样式丢失问题

在main.ts文件下单独引入丢失组件的全局变量,如果messageBox里按钮样式也丢失,也需要再引入一次button样式

    import 'element-plus/theme-chalk/el-loading.css'
    import 'element-plus/theme-chalk/el-button.css'
    import 'element-plus/theme-chalk/el-message-box.css'

2.在vue文件下和ts文件下使用路由

// 路由的路径及代码  @/router/index.ts
import  * as VueRouter from 'vue-router'
// 路由导入使用动态导入
const Layout = () => import('../layout/index.vue')
const Home = () => import('../view/home/Home.vue')
const Login = () => import('../view/login/Login.vue')

const routes: Array<VueRouter.RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    redirect: '/home',
    component: Layout,
    children: [
      {
        name: 'Home',
        path: '/home',
        component: Home
      }
    ]
  }  
]
const router: VueRouter.Router = VueRouter.createRouter({
    // 使用 hash 模式。
    history: VueRouter.createWebHashHistory(),
    routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  if (getTargetCookie(cookieName) && to.name === 'Login') {
    return false
  } else {
    next()
  }
})
export default router

// Login.vue  vue文件使用路由
<script lang="ts" setup>
  import { useRouter } from 'vue-router'
  const router = useRouter()
  router.push({
    name: 'Home'
  })
</script>
// request.ts里进行路由跳转,直接引入上面router.vue对象,使用router.vue里面的router对象进行跳转
import VueRouter from '@/router/index'
// 路由跳转
VueRouter.push({
  name: 'Login'
})

3.安装element-plus后报错Failed to parse source for import analysis because the content contains invalid JS syntax. Install @vitejs/plugin-vue to handle .vue files

image.png

解决方案:

npm install @vitejs/plugin-vue

// 在vite.config.ts或vite.config.js文件增加下面代码
import vue from '@vitejs/plugin-vue';
export default defineConfig({
  plugins: [
    vue()
  ]
})

4.vite设置环境变量

index.html同级目录下设置.env.[mode],具体配置看这里,配置如图:

// .env.development文件
VITE_APP_URL = "http://localhost:8008/"
VITE_APP_TITLE = "测试"
// tsconfig.json文件增加
{
  "compilerOptions": {
      "types": ["vite/client"],
  }
}
// 在vue文件里获取方式
console.log(import.meta.env)