快速创建vite项目

128 阅读1分钟
  • 安装依赖
npm init vite
// 或者使用 yarn
yarn create vite
  • 填写项目名

  • 选择vue

  • 选择所需语言,根据需要选择即可

  • 完成后输入 指令,运行即可

安装router

  • 安装依赖
 npm install vue-router -S
  • 创建router/index.js
import { createRouter, createWebHistory } from "vue-router";

const routes = [
    {
        path: "/",
        name: "test",
        component: () =>import( "../views/test.vue"),
    },
];
const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;
  • 在main.js中引入
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router";

createApp(App).use(router).mount('#app')

在目录中新增了/views/test.vue

使用Pinia(替代原先的vuex)

可先了解一下Pinia(文档地址:pinia.web3doc.top/introductio…)

  1. 安装使用
npm install pinia
# 或者使用 yarn
yarn add pinia
  • 创建store/index.js
import { createPinia } from 'pinia'

const pinia = createPinia()

export default pinia
  • 在main.js中引入
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router";
import pinia from './store'

createApp(App).use(router).use(pinia).mount('#app')
  • 按模块来区分,创建store/modules/test
import { defineStore } from 'pinia'
import { ref } from 'vue'

const useTestStore = defineStore('test', () => {
    const num = ref(0)

    const add = () => {
        num.value++
    }

    return {
        num,
        add
    }
})

export default useTestStore
  • 引入到test.vue中
<template>
    <button @click="handleChangeNum">add</button>
    <span>{{ num }}</span>
</template>
<script setup>
import useTestStore from '../store/modules/test.js'
const testStore = useTestStore()

import { storeToRefs } from 'pinia'
const { num } = storeToRefs(testStore)

const handleChangeNum = () => {
    num.value++
    // 或者
    // testStore.add()
}

</script>

使用less

  • 安装依赖
npm install less
npm install less-loader
  • vite.config.js配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  css: {
    // 预处理器配置项
    preprocessorOptions: {
      less: {
        math: "always",
      },
    },
  }
})

使用@引入

在以上示例中都使用../来引入,如需使用@按以下步骤配置即可

  • vite.config.js配置
import { defineConfig } from 'vite'
import { resolve } from 'path';
import vue from '@vitejs/plugin-vue'

const pathResolve = (dir) => {
  return resolve(__dirname, ".", dir)
}


export default defineConfig({
  plugins: [vue()],
  css: {
    // 预处理器配置项
    preprocessorOptions: {
      less: {
        math: "always",
      },
    },
  },
  resolve: {
    alias: {
      '@': pathResolve('src'),
    }
  },
})