首页 > 其他分享 >新建vite vue2 项目

新建vite vue2 项目

时间:2024-04-19 15:25:32浏览次数:21  
标签:vue 新建 App js vue2 router import vite

1.1 创建项目
注意:这里vite的版本采用2.8.0的,最新的版本创建后续会出现问题

npm init [email protected]
后续,安装如图

 

 

创建好项目后依次运行以下命令

// 1.进入项目
cd vite-vue2

// 2.安装依赖
npm install

// 3.启动项目
npm run dev
访问效果如下

 

 

1.2 安装vite对vue2支持的插件
在vite-vue2安装:vite-plugin-vue2

// 注意:vite-plugin-vue2的版本为1.9.3
npm install [email protected] -D
在根目录创建vite.config.js文件,来注册插件

import { defineConfig } from 'vite' // 动态配置函数
import { createVuePlugin } from 'vite-plugin-vue2'
import { resolve } from 'path'

export default () =>
defineConfig({
plugins: [createVuePlugin()],
server: {
open: true, //自动打开浏览器
port: 1567 //端口号
},
resolve: {
// 别名
alias: [
{
find: '@',
replacement: '/src'
}
]
}
})
1.3 安装vue依赖
npm命令安装

npm install [email protected] [email protected] -S
1.4 修改项目文件结构
1.4.1 创建src目录
在项目根目录下创建src目录,然后修改main.js并将其移入src目录里

import Vue from 'vue'
import App from './App.vue'

new Vue({
render: h => h(App)
}).$mount('#app')
1.4.2 修改index.html
修改项目启动的入口文件

// index.html
<script type="module" src="/src/main.js"></script>
1.4.3 src目录下创建App.vue文件
代码如下:

<template>
<div>Hello Vite Vue2</div>
</template>
1.5 运行一下项目
再次运行下项目检验一下之前配置有无问题

npm run dev


2、vue-router
2.1 安装
npm install [email protected] -S
2.2 新建router目录
2.2.1 创建路由表
在src目录下创建router目录,并在router目录下创建index.js文件和module目录,在module目录下创建home.js和index.js。这里采用分模块来存放路由表

// /src/router下index.js
import { module } from './module/index'
import VueRouter from 'vue-router'
import Vue from 'vue'

// 使用VueRouter
Vue.use(VueRouter)

const routes = [
...module
]

const router = new VueRouter({
mode: 'history',
base: '/',
routes
})

export default router
// /src/router/module/home.js
export const home = [
{
path: '/home',
meta: { title: '首页' },
component: () => import('@/views/home/Index.vue')
}
]
// /src/router/module/index.js
import { home } from './home'

export const module = [...home]
2.2.2 创建路由指向的页面组件
在 src 目录下创建 views 目录,用来存放页面组件。

在 src/views/home 目录下创建1个页面:Index.vue

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

<script>
export default {
name: "Index.vue"
}
</script>

<style scoped>

</style>
2.3 全局注册
2.3.1 在main.js里注册
import Vue from 'vue'
import App from './App.vue'
import router from './router/index.js'//引入router路由

new Vue({
router,//注册router路由
render: h => h(App)
}).$mount('#app')
2.3.2 创建路由跳转标签
修改App.vue文件

<template>
<div id="app" class="app">
<router-view></router-view>
</div>
</template>
3、vuex(可选)
vuex作为大型单页面的状态管理器,使用起来十分方便,在有mapState、mapMutation等语法糖的引入变得更加的简单,但当项目比较小的时候可以不引入,可能会变得臃肿起来,这里为了学习就引入进来了~

3.1 安装
npm install [email protected] -S
3.2 新建vuex目录
在src目录下创建store目录,并在store目录下创建index.js

// index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // 使用Vuex
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {},
modules: {}
})
3.3 全局注册
import Vue from 'vue'
import App from './App.vue'
import router from './router/index.js'
import store from './store'

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
4、组件库
这里组件库我采用了element-ui,注意不是plus版本plus版本是Vue3的

引入方式参考官方文档

4.1 安装
npm i element-ui -S
4.2 完整引入
在 main.js 中写入以下内容:

import Vue from 'vue'

import ElementUI from 'element-ui';//引入ElementUI组件库
import 'element-ui/lib/theme-chalk/index.css';//引入ElementUI样式
import App from './App.vue'
import router from './router/index.js'//引入router路由

Vue.use(ElementUI);//注册ElementUI

new Vue({
router,//注册router路由
render: h => h(App)
}).$mount('#app')

4.3 按需引入参考文档操作
Element - The world's most popular Vue UI framework

5、axios
5.1 安装
npm install axios -S
5.2 封装axios
在src创建http目录,在其下面创建request.js和home.js

// request.js
import axios from 'axios'
import {Message, Loading} from 'element-ui';

//创建loading实列
let loadingInstance = undefined

// 创建axios实例
// 创建请求时可以用的配置选项

// 配后端数据的接收方式application/json;charset=UTF-8或者application/x-www-form-urlencoded;charset=UTF-8
const contentType = 'application/json;charset=UTF-8'

const apiUrl = 'http://ip:port/XXXAPI'

const instance = axios.create({
/**
* 是否携带cookie,注意若携带cookie后端必须配置
* 1.Access-Control-Allow-Origin为单一域名(具体到IP + port,用localhost貌似不行)
* 2.需要带上响应头Access-Control-Allow-Credentials
*/
// withCredentials: true,
timeout: 60000,
baseURL: apiUrl,
headers: {
'Content-Type': contentType
}
})
// axios的全局配置
instance.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded'
}
instance.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
}
//instance.defaults.headers['Access-Control-Allow-Origin']='*'

// 添加请求拦截器(post只能接受字符串类型数据)
instance.interceptors.request.use(
config => {
if(config.loading === undefined || config.loading === true){
loadingInstance = Loading.service({
lock: true,
text: '接口请求中...',
background: 'rgb(0 120 212 / 28%)'
})
}
return config
},
error => {
if (loadingInstance) {
loadingInstance.close()
}
return Promise.reject(error)
}
)
const errorHandle = (status, other) => {
switch (status) {
case 400:
Message.error('信息校验失败')
break
case 401:
Message.error('认证失败')
break
case 403:
Message.error('token校验失败')
break
case 404:
Message.error('请求的资源不存在')
break
default:
Message.error(other)
break
}
}

// 添加响应拦截器
instance.interceptors.response.use(
// 响应包含以下信息data,status,statusText,headers,config
res => {
// 请求通用处理
if (loadingInstance) {
loadingInstance.close()
}
return res.data
},
err => {
if (loadingInstance) {
loadingInstance.close()
}
// Message.error(err)
const {response} = err
if (response) {
errorHandle(response.status, response.data)
return Promise.reject(response)
}
Message.error('请求失败')
return true
}
)

export default instance
import request from './request'

export default {
getList(model) {
return request({
url: '/theme/list',
method: 'post',
data: model
})
},
}
5.3 在页面中使用
<script>
import $http from '@/http/home.js'
export default {
mounted() {

},
methods: {
async onSubmit(){
const res = await $http.getList({});
console.log(res)
}
}
}
</script>
————————————————


原文链接:https://blog.csdn.net/weixin_37947181/article/details/130617988

标签:vue,新建,App,js,vue2,router,import,vite
From: https://www.cnblogs.com/hjyjack9563-bk/p/18145943

相关文章

  • vitepress搭建博客
    vitepress搭建博客之前使用的Hugo搭建了一个博客,感兴趣的可以看看Hugo搭建个人博客,使用了一段时间,配置完成后使用还是相对简单的,不过总感觉不够顺手,后来看到vitepress,就尝试了一下,感觉使用更顺手一些,所以打算换成vitepress,下面记录一下搭建的过程。搭建博客流程关于使用vitep......
  • 信创里程碑:Tapdata 同时通过华为云 GaussDB 及鲲鹏兼容互认证,全面支持基础设施自主创
    近日,深圳钛铂数据有限公司(以下简称钛铂数据)自主研发的钛铂实时数据平台(TapdataLiveDataPlatform)分别与华为云GaussDB、华为云公有云平台(鲲鹏)完成相互兼容性测试,经功能、性能、安全三轮测试显示,TapdataLiveDataPlatform与二者兼容性良好,系统功能正常,运行稳定,顺利获得华为云......
  • Vue3 + vite 项目自定义一个svg-icon组件
    1.安装vite-plugin-svg-icons插件npmivite-plugin-svg-icons-D2.vite.config.ts中配置importpathfrom"path";import{createSvgIconsPlugin}from"vite-plugin-svg-icons";exportdefaultdefineConfig({plugins:[......createS......
  • SpreadsheetControl组件修改,拖拽、新建、打开文件在独立浮窗打开
    一、修改文件拖拽功能,使其能够在另外一个独立窗体打开,需要配合documentManager控件实现。实现后效果:将11.xlsx文件拖拽到工作区 1.创建XExceluserControl用户窗体,代码如下:publicpartialclassXExcelUserControl:DevExpress.XtraEditors.XtraUserControl{publi......
  • vue2 mixin 和 vue3 hook
    mixin1.逻辑函数的复用2vue组件中的选项式API(例如:data,computed,watch)或者组件的生命周期钩子(created、mounted、destroyed)使用方法mixins:[mixins],//注册mixin,这样mixin中所有的钩子函数等同于组件中钩子1mixin中的生命周期函数会和组件的生命周期函数一起合并执行。2......
  • VUE:vite添加环境变量(一)
    新建'.env'(和vite.config.js同一个路径下)VITE_APP_API_URL=http://localhostvite.config.jsimport{defineConfig,loadEnv}from'vite'exportdefaultdefineConfig((mode)=>{constenv_config=loadEnv(mode,process.cwd())constV......
  • vue2项目 network无法访问此网站
    vue2项目启动后,local可以访问,但是network不能访问防火墙等等都检查了查到原因如下:本来写的是这样,实际上端口号需要保持一致devServer:{disableHostCheck:true,open:true,host:'0.0.0.0',port:8002,https:false,hotOnly:false,public......
  • vue2响应式原理
    vue2响应式原理classDep{constructor(){//依赖保存器this.subscribers=newSet();}//收集依赖depend=()=>{if(activeEffect){this.subscribers.add(activeEffect);}};//通知收集的依赖notify=()=>{this.......
  • WPF新建viewModel实例化成员的注意事项
    不要用表达式体去初始化一个用做数据源(比如ItemSource)的引用类型成员。比如这种publicList<MainWindowItem>Items=>newList<MainWindowItem>(){newMainWindowItem{title="项目管理",icon="\ue613",type=typeof(项目管理Control),group="内部管理"},new......
  • VUE2.0版本学习笔记
    VUE2.0版本学习笔记脚手架安装npminstall-g@vue/clivuecreatevue2-practice#选择2.0版本如果执行中遇到错误,yarn的错误certificatehasexpired则执行yarncachecleanyarnconfigsetstrict-sslfalsecdvue2-practicenpmrunserve#初学者建议安装vsco......