0
点赞
收藏
分享

微信扫一扫

【Vue技术栈开发基础指南】

千行 2022-02-14 阅读 41

Vue前端开发框架

Vue-Cli项目脚手架 基于vue.js进行快速开发的完整系统
文档地址 https://cli.vuejs.org/zh/
  1. 安装node.js https://nodejs.org/zh-cn/
  2. 安装vue-cli脚手架
npm install -g @vue/cli

  1. 创建一个vue项目
执行命令 vue create hello-world(项目名) 快速创建一个vue项目

1) 执行命令后会提示你选择什么样的预先配置,我们选择Manually select features 手动选择配置
2) Check the features needed for your project 空格选中需要的元素
     (*) Choose Vue version  // 选择vue版本
     (*) Babel // javascript语法编译器
     ( ) TypeScript
     ( ) Progressive Web App (PWA) Support
     (*) Router // vue-router路由管理器
     (*) Vuex  // 状态管理器
    >(*) CSS Pre-processors // 选择CSS预处理器
     (*) Linter / Formatter // 选择格式化和校验规则
     ( ) Unit Testing

  1. 启动项目 在终端使用命令运行,查看package.json文件的scripts中命令的定义,然后使用npm run '命令名’来执行
    例如: npm run serve ,npm run build ,npm run serve:prod
{
  "name": "trechkpcadminview",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "serve:prod": "vue-cli-service serve --mode production",
    "lint": "vue-cli-service lint"
  },
  ...

  1. 项目的模式以及环境变量

    模式

    模式是 Vue CLI 项目中一个重要的概念

    • - 默认情况下,一个 Vue CLI 项目有三个模式

    • development 模式用于 vue-cli-service serve

      development
    • test 模式用于 vue-cli-service test:unit

      test 模式会创建一个优化过后的,并且旨在用于单元测试的 webpack 配置,它并不会处理图片以及一些对单元测试非必需的其他资源
    • production 模式用于 vue-cli-service build

      production 模式会创建一个优化过后用于在生产环境中的webpack配置
    • 你可以通过传递 --mode选项参数为命令行覆写默认的模式。例如,如果你想要在构建命令中使用开发环境变量

    vue-cli-service build --mode development
    // 当运行 vue-cli-service 命令时,所有的环境变量都从对应的环境文件中载入
    
    环境变量

    你可以在你的项目根目录中放置下列文件来指定环境变量:

    // 这是环境文件
    .env                # 在所有的环境中被载入
    .env.local          # 在所有的环境中被载入,但会被 git 忽略
    .env.[mode]         # 只在指定的模式中被载入
    .env.[mode].local   # 只在指定的模式中被载入,但会被 git 忽略
    

    环境文件中指定环境变量是key=value的形式,如果环境文件中不包含NODE_ENV这个变量,它的值将取决于模式,例如,在 production 模式下被设置为 “production”,在 test 模式下被设置为 “test”,默认则是 “development”。

    NODE_ENV 将决定您的应用运行的模式,是开发,生产还是测试,因此也决定了创建哪种 webpack 配置。

    一个环境文件只包含环境变量的“键=值”对:

    FOO=bar
    VUE_APP_NOT_SECRET_CODE=some_value
    
    // 只有 NODE_ENV,BASE_URL 和以 VUE_APP_ 开头的变量将通过 webpack.DefinePlugin 静态地嵌入到客户端侧的代码中
    
    // 可以在应用的代码中这样访问它们
    console.log(process.env.VUE_APP_SECRET)
    
Vue核心插件vue-router官方路由管理器
文档地址:https://router.vuejs.org/zh/

通过组合组件来组成应用程序我们要做的就是将组件 (components) 映射到路由 (routes) 然后告诉 Vue Router 在哪里渲染它们

// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

const Menu= ()=>import(/* webpackChunkName: "basic" */ '@/views/basic/menu')

// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar },
  { path: '/menu', component: Menu },
]

// 3. 创建 router 实例,然后传 `routes` 配置
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
  router
}).$mount('#app')
  1. 创建一个Router实例
let router=new VueRouter({
  routes: [
    // 动态路径参数 以冒号开头
    { path: '/user/:id', component: User }
  ]
})
// router 就是实例对象 有很多实例对象的api可以调用 具体查阅文档
  1. Router常用实例方法
// 路由跳转的实例方法
router.push(location, onComplete?, onAbort?)
router.push(location).then(onComplete).catch(onAbort)
router.replace(location, onComplete?, onAbort?)
router.replace(location).then(onComplete).catch(onAbort)
router.go(n)
router.back()
router.forward()

  1. 路由的全局导航守卫
router.beforeEach((to, from, next) => {  // 前置守卫 在路由进入之前执行 
  /* 必须调用 `next` */
})

router.afterEach((to, from) => {}) // 后置守卫 在路由进入后执行
  1. 组件内的路由守卫

    • beforeRouteEnter
    • beforeRouteUpdate
    • beforeRouteLeave
  2. 常用路由对象属性

    $route.path // 当前路由的路径
    $route.params // 一个 key/value 对象 有路由参数,就是一个空对象
    $route.query // 一个 key/value 对象,表示 URL 查询参数 对于路径/foo?user=1,则有 $route.query.user == 1,如果没有查询参数,则是个空对象
    $route.fullPath // 完成解析后的 URL,包含查询参数和 hash 的完整路径
    $route.matched // 一个数组,包含当前路由的所有嵌套路径片段的路由记录
    ...

  1. HTML5 History 模式


Vue核心插件vuex 状态管理插件
文档地址:https://vuex.vuejs.org/zh/
State
Getters
Mutations
Actions

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
实际在项目中使用
  1. 安装 npm install vuex
  2. 在store文件夹下的index.js 引入vue和vuex
// src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
  1. 创建vuex的store对象并设置核心对象state,getters,mutations,actions
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

export default store
  1. 将vuex的store对象注入vue实例对象中
import store from './store'

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

Axios 是一个基于 promise 的 HTTP 库

axios 依赖原生的 ES6 Promise 实现而被支持

文档地址:https://www.kancloud.cn/yunye/axios/234845
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
1. 创建实例
// axios的create 方法返回一个axios实例
var service = axios.create({
  baseURL: 'https://pd.t-rech.com/reception',
  timeout: 10000,
  
  ...
});
2. 实例方法
request(config)
get(url[, config])
delete(url[, config])
head(url[, config])
post(url[, data[, config]])
put(url[, data[, config]])
patch(url[, data[, config]])

3. axios的常用请求配置
// config 常用配置参考如下

{
  // `url` 是用于请求的服务器 URL
  url: '/user',

  // `method` 是创建请求时使用的方法
  method: 'get', // 默认是 get

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',

  // `headers` 是即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` 是即将与请求一起发送的 URL 参数
  params: {
    ID: 12345
  },
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,

  ...

}
4. 响应结构
{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}
5. 自定义axios实例以及设置全局默认值
// 创建实例时设置配置的默认值
var service = axios.create({
  baseURL: 'https://pd.t-rech.com/reception',
  timeout: 10000,
  
  ...
});
或者 service.defaults.baseURL = 'https://pd.t-rech.com/reception; 
6. 拦截器
请求拦截器
// 添加请求拦截器
service.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

请求拦截器在项目实战过程中比较常用到的是把已有的token配置到请求头中去,进行统一的token请求头的设置,例如:

service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
响应拦截器
// 添加响应拦截器
service.interceptors.request.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

  1. 响应拦截器在项目实战过程中比较常用到的就是把接口中响应头中token拿到,并把之前保存下来的token进行更新。
  2. 处理返回的数据,进行统一的数据包装,让接口返回的数据格式统一规范
    例如:
service.interceptors.response.use(

  response => {
    const { authorization } = response.headers
    if (authorization) {
      setToken(authorization)
    }
    const res = response.data

    if (res.code !== 'S_00001') {
      // E_30019 E_30011 会话失效
      if (res.code === 'E_30019' || res.code === 'E_30011') {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      Message({
        showClose: true,
        type: 'error',
        message: res.msg
      })

      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message || '请求错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
举报

相关推荐

0 条评论