Vuejs实战项目步骤一

1、使用vue初始化项目

vue create msm-demo  #创建项目

npm run serve    #部署

2、更改public文件夹下面的index文件,只留下

<div id="app"></div>

3、创建配置vue.config.js
module.exports = {
    devServer: {
        port: 8888,     //端口号,如果端口号占用,会自动提升1
        host: "localhost",  //主机名,127.0.0.1,真机:0.0.0.0
        https: false,   //协议
        open: false,    //启动服务时自动打开浏览器访问

    },

    lintOnSave: false,  //关闭格式检查
    productionSourceMap: false, // 打包时不会生成.map 文件,加快打包速度
}

4、整合第三方库

1、安装axios,处理异步请求

npm i -S axios

2、安装pubsub-js,实现非父子组件间通信

npm i -S  pubsub-js

3、查看package.json中是否有对应依赖


5、整合ElementUI

1、npm安装:

npm i element-ui -S

2、编辑main.js

import Vue from "vue";
//引入组件库
import ElementUI from 'element-ui';
//引入样式
import 'element-ui/lib/theme-chalk/index.css';

import App from "./App.vue";
import router from "./router";

//使用ElementUI
Vue.use(ElementUI);

//报错是否全,开发环节位false,生产环节为true
Vue.config.productionTip = process.env.NODE_ENV === 'production';   //开发环境 development,生产环境 production
console.log(process.env.NODE_ENV)

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

6、Axios封装和跨域问题

1、封装Axios对象  github:https://github.com/axios/axios

(自己封装的Axios在后续可以使用axios中提供的拦截器)

  1、在src目录下创建utils目录及utils下面创建request.js文件,自己创建axios对象

// 导入axios
import axios from 'axios'

// 原来axios发送请求,在public文件夹下的文件可以不指定public,/db.json默认查找public文件夹下的文件
// axios.get('/db.json').then(response => {
//     const data =  response.data
//     console.log(data)
// })

// 自己创建axios对象
const request = axios.create({
    //基础路径
    baseURL: '/',
    timeout: 5000   //请求超时
})

//使用自定义的axios对象发送请求
// request.get('/db.json').then(response => {
//     console.log(response.data)
// })

// 请求拦截器
//使用自定义的axios对象
request.interceptors.request.use(config => {
    // 请求拦截
},err =>{
    // 出现异常
    // 使用ES6的语法
    return Promise.reject(error);
})

// 响应拦截器
request.interceptors.response.use(response =>{
    // response.data
    return response
},error =>{
    return Promise.reject(error);
})


// Add a request interceptor
// axios.interceptors.request.use(function (config) {
//     // Do something before request is sent
//     return config;
//   }, function (error) {
//     // Do something with request error
//     return Promise.reject(error);
//   });

// // Add a response interceptor
// axios.interceptors.response.use(function (response) {
//     // Any status code that lie within the range of 2xx cause this function to trigger
//     // Do something with response data
//     return response;
//   }, function (error) {
//     // Any status codes that falls outside the range of 2xx cause this function to trigger
//     // Do something with response error
//     return Promise.reject(error);
//   });


// 导出自定义创建的axios对象,导出后别人就可以使用此对象
export default request

2、在src文件夹下创建api文件夹,api文件夹放调用api接口的文件,src可用@表示,哪个组件要引用对应的api,就可以直接从api文件夹中进行api的引用

/api/test.js:

import request from '@/utils/request'


const BASE_URL = '/dev-api'

// 这里直接调用对应的方法发送请求
// request.get('/db.json').then(response => {
//     console.log(response.data)
// })

//测试2,以对象配置的方式进行指定请求方式
//开发过程中,一般采用这种方法
request({
    method: 'get',
    url: BASE_URL + '/db.json'
}).then(response =>{
    console.log('get2',response.data)
})


//导出一个默认对象
export default {
    //定义方法
    getList() {
        //返回一个对象
        const req = request({
            method: 'get',
            url: BASE_URL + 'db.json'
        })
        return req
    }
}

/components/Helloworld.vue:调用接口

import testApi from '@/api/test'

export default {

  data() {
    return {
      list: []
    }
  },

  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      testApi.getList().then(response => {
        console.log('get3',response.data)
        this.list = response.data
      })
    }
  },

3、跨域现象:

前后端分离时,前端和后端API服务器可能不在同一台主机上,就存在跨域问题,浏览器限制了跨域访问

同源策略:是指协议,域名,端口都要相同,其中有一个不同都会产生跨域

解决开发环境跨域问题:

  配置代理https://cli.vuejs.org/zh/config/#devserver:通过 vue.config.js 中的 devServer.proxy 选项来配置。

proxy: {    //开发环境代理配置
            // 配置前缀
            '/dev-api': {
                //  目标服务器地址,代理访问 http://localhost:8001
                target: 'http://localhost:8001',
                changeOrigin: true,  //开启代理转发
                pathRewrite: {
                    // /dev-api/db.json 最终会转发到http://localhost:8001/db.json
                    '^/dev-api': '',    //此设置将请求地址前缀 /dev-api 替换为空
                }
            }
        }

7、配置不同环境 常量值

https://cli.vuejs.org/zh/guide/mode-and-env.html

# 只有以 VUE_APP_ 开头的变量会被 webpack 静态嵌入到项目中进行使用 process.env.VUE_APP_XXXX

 分别配置.env.development和.env.production

.env.development:

# 目标服务接口地址,这个地址时按照自己环境进行配置,添加或者更改配置后,需要重新启动服务
VUE_APP_SERVICE_URL = 'http://localhost:8001'

# 开发环境的前缀
VUE_APP_BASE_API = '/dev-api'

.env.production:

# 只有以 VUE_APP_ 开头的变量会被 webpack 静态嵌入到项目中进行使用

VUE_APP_BASE_API = '/pro-api'

调用例子:

proxy: {    //开发环境代理配置
            // 配置前缀
            // '/dev-api': {
            [process.env.VUE_APP_BASE_API]: {
                //  目标服务器地址,代理访问 http://localhost:8001
                target: process.env.VUE_APP_SERVICE_URL,
                changeOrigin: true,  //开启代理转发
                pathRewrite: {
                    // /dev-api/db.json 最终会转发到http://localhost:8001/db.json
                    // '^/dev-api': '',    //此设置将请求地址前缀 /dev-api 替换为空
                    ['^' + [process.env.VUE_APP_BASE_API]]: ''
                }
            }
        }
原文地址:https://www.cnblogs.com/flypig666/p/11576662.html