采用cli脚手架方式快速搭建项目

1.确保本机已安装nodejs和npm

执行下列命令安装vue

2.切换淘宝镜像可以多执行几次    

npm config set registry http://registry.npm.taobao.org

3.安装cli  脚手架官网链接:安装 | Vue CLI

npm install -g @vue/cli 

4.创建项目  

vue create hello-world

运行后让选择创建方式,此处使用默认配置创建直接回车,创建项目时可能会卡主,导致部分未安装,在启动时根据报错信息尝试执行单独命令安装

5.尝试启动  ,在代码根目录下执行(切换到代码根目录下,按住ctrl+鼠标右键,打开powrshell

npm  run serve

启动失败:

启动可能存在多种问题,可以执行 npm i  然后  npm install eslint 或者根据报错百度解决方案出现了vue create时提示无法从xxx获取返回,此时切换路由又切换回 因为公司限制外网访问所以要固定ip,然后执行npm i 成功后,再去执行 npm install eslint 会报错,需要切换完wifi之后直接执行npm install eslint

项目创建完成且能正常启动后,使用element作为UI框架,vue3.0使用的是element plus

官网链接:一个 Vue 3 UI 框架 | Element Plus

以下操作在代码根目录下执行

6.引入element-plus

参考vue3引入Element-plus详细步骤_疑似忘川落九天的博客-CSDN博客_vue3引入elementplus

npm install element-plus

  在项目内引入element,src->main.js

import { createApp } from 'vue'
import App from './App.vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'




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

7.访问后台接口需要引入axios

npm install axios

使用vscode打开代码,在vue.config.js配置axios跨域,顺便关闭命名语法检查否则可能会在创建新页面时因为命名问题运行报错

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,//驼峰命名语法检查
  //配置axios跨域
  devServer: {
      proxy: {
          '/api': {
              target: 'http://localhost:9384',
              // 允许跨域
              changeOrigin: true,
              ws: true,
              pathRewrite: {
                  '^/api': ''
              }
          }
      }
  }
})

可对axios的请求进行封装

新建文件src=>request=>index.js

import axios from 'axios'

// 创建一个 axios 实例
const service = axios.create({
	baseURL: '/api', // 所有的请求地址前缀部分
	timeout: 60000, // 请求超时时间毫秒
	withCredentials: true, // 异步请求携带cookie
	headers: {
		// 设置后端需要的传参类型
		'Content-Type': 'application/json',
		'X-Requested-With': 'XMLHttpRequest',
	},
})

// 添加请求拦截器
service.interceptors.request.use(
	function (config) {
		// 在发送请求之前做些什么
        console.log(service);
		return config
	},
	function (error) {
		// 对请求错误做些什么
		console.log(error)
		return Promise.reject(error)
	}
)

// 添加响应拦截器
service.interceptors.response.use(
	function (response) {
		console.log(response);
        return response;
	},
	function (error) {
		// 超出 2xx 范围的状态码都会触发该函数。
		// 对响应错误做点什么
		console.log(error)
		return Promise.reject(error)
	}
)

export default service

src=>apis=>login.ts

// 导入axios实例
import httpRequest from '@/request/index.js'

// 登录
export function login(param) {
    return httpRequest({
		url: 'api/Login/login',
		method: 'post',
		data: param,
	})
}

使用方法

    import { login } from '../apis/login.ts'
    const param = {
       username: form.username,
       password: form.password,
       ClientType: "PC",
       ClientKey: ClientKey,
       ClientIP: ""
    }
    console.log(param)
    login(param).then((res) => {
        console.log(res);
    })

8.引入vue-router路由

npm install vue-router@4.0.0-beta.13

参考https://www.jianshu.com/p/ca0615a8ce08,但是按文章实现时有一点问题

可先按下面的步骤实现

创建文件src=>route=>index.js

import { createRouter, createWebHashHistory } from "vue-router"


const routes = [
  { path: "/", redirect: "/login" },
  {
    path: "/home",
    name: "home",
    component: () => import("../components/HelloWorld.vue")

  },
  {
    path: "/login",
    name: "login",
    component: () => import("../components/Login.vue")

  }
]
 const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})
// 4. 你还可以监听路由拦截,比如权限验证。
router.beforeEach((to, from, next) => {
  console.log(to);
  console.log(from);
  console.log(router);
  if(to.name=='home'){
    return router.replace({
      name: 'demo'
    })
  }
  next();
})
export default router;

修改App.vue文件

<template>
  <div id="app">
  <!-- 路由出口 -->
  <!-- 路由匹配到的组件将渲染在这里 -->
  <router-view></router-view>
</div>
</template>
<script>
export default {

}
</script>
<style scoped>

</style>

在main.js中引用

import { createApp } from 'vue'
import App from './App.vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './route/index.js'



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

创建文件src——components——login.vue

<template>
    <el-row :gutter="0">
      <el-col :span="6">
      </el-col>
      <el-col :span="12">
        <el-form :model="form" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.password" type="password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
      </el-col>
    </el-row>
  </template>
   
  <script  setup>
  import { reactive } from 'vue'
  import { encryp } from '../apis/crypto.ts'
  import { login } from '../apis/login.ts'
  import { useRouter } from 'vue-router'
  
  const router = useRouter()
  // do not use same name with ref
  const form = reactive({
    username: '',
    password: ''
  })
  
  const onSubmit = () => {
    var timestamp = new Date().getTime();
    console.log(timestamp);
    var ClientKey = encryp('g459e0c557ae4650b19169e4dbvgnhly', '1472583690123456', timestamp);
    const param = {
      username: form.username,
      password: form.password,
      ClientType: "PC",
      ClientKey: ClientKey,
      ClientIP: ""
    }
    console.log(param)
    login(param).then((res) => {
      if(res.data.Code=='200'){
        $cookies.config("1m");
        $cookies.set('tokenforvue',res.data.Data.key);
        router.push({
          name: 'home'
        })
      }else{
        ElMessage(res.data.Msg)
      }
    })
  };
  

  
  </script>
  

 此处有两处踩坑,一是在route=>index.js文件中,参考文章是直接输出了方法这种写法存在问题,而我这边先定义后输出,页面正常;还有就是调用切换路由方法,const router = useRouter(),这个需要放在方法外,因为是异步创建,如果使用时再去创建,会导致router未定义报错

9.引入vue-cookie

执行命令引入插件

npm install vue-cookies --save

引入main.js

import cookies from 'vue-cookies'



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

使用

//设置时效1月
 $cookies.config("1m");
//设置cookie的值
 $cookies.set('tokenforvue',res.data.Data.key);

Logo

前往低代码交流专区

更多推荐