Vuejs實戰項目步驟一

一、使用vue初始化項目css

vue create msm-demo  #建立項目

npm run serve    #部署

 

二、更改public文件夾下面的index文件,只留下html

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

三、建立配置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 文件,加快打包速度
}

 

四、整合第三方庫前端

一、安裝axios,處理異步請求vue

npm i -S axios

二、安裝pubsub-js,實現非父子組件間通訊webpack

npm i -S  pubsub-js

三、查看package.json中是否有對應依賴ios


五、整合ElementUIgit

一、npm安裝:github

npm i element-ui -S

二、編輯main.jsweb

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");

六、Axios封裝和跨域問題npm

一、封裝Axios對象  github:https://github.com/axios/axios

(本身封裝的Axios在後續可使用axios中提供的攔截器)

  一、在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

二、在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
      })
    }
  },

三、跨域現象:

先後端分離時,前端和後端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 替換爲空
                }
            }
        }

七、配置不一樣環境 常量值

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]]: ''
                }
            }
        }
相關文章
相關標籤/搜索