vue項(xiàng)目搭建步驟vue-cli+webpack+axios+router

前提是你已安裝好node,以下步驟都是mac環(huán)境,window稍微有點(diǎn)區(qū)別,區(qū)別不大,不做描述

1.安裝腳手架vue-cli

sudo npm install -g vue-cli
vue.jpeg

2.安裝webpack

sudo npm install -g webpack

3.用webpack初始化項(xiàng)目,項(xiàng)目名稱vueDemo

vue init webpack vueDemo

4.項(xiàng)目描述文件配置

vue init webpack vueDemo

Project name vue-demo
? Project description a single vue project
? Author mxp
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No

5.安裝依賴

npm install

6.啟動(dòng)項(xiàng)目

npm run dev

7.壓縮構(gòu)建項(xiàng)目

npm run build

8.集成router

1.main.js
import VueRouter from 'vue-router';
import Router from './router/index.js';

Vue.use(VueRouter);

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

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
});
2. router/index.js
import CarList from '@/components/car/car_list/CarList';
import CarListContent from '@/components/car/car_list/CarListContent';
import CarDetail from '@/components/car/CarDetail';

export default [
  {
        path: '/',
        meta: {title: '找車'},
        component: CarList,
        children: [
            {
                path: '',
                name: 'CarListContent_Default',
                component: CarListContent,
            }
        ],
    },
    // car detail
    {
        path: '/car/CarDetail/:car_id/:distance',
        meta: {title: '車輛詳情頁'},
        name: 'car_CarDetail',
        component: CarDetail,
        props: true,
    },
];

9.集成sass

1. 安裝sass依賴
npm install node-sass --save-dev
npm install sass-loader --save-dev
2.使用sass,在style標(biāo)簽上加lang="sass"
<style lang="sass">
@import './assets/css/normalize.css';
@import './assets/css/sassAttr.scss';
@import './assets/css/sassFn.scss';
@import './assets/css/common.scss';

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

10.集成axios

1.安裝
npm install --save axios vue-axios
2.在main.js引入
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios);
3.頁面使用
var self = this;
self.axios
    .post('https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/example/order_list')
    .then((response) => {
        console.log(response.data);
    });

11.vue-cli本地環(huán)境API代理設(shè)置和解決跨域

1.修改config下面的index.js的dev
proxyTable: {
  '/api': {
        target: 'https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/example',
        secure: false,// 如果是https接口,需要配置這個(gè)參數(shù)??不確定是否需要
        changeOrigin: true,// 是否跨域
        pathRewrite: {
            '^/api': '',
        },
    }
},
2.重新構(gòu)建項(xiàng)目
node build/build.js
3.本地hosts配置
/etc/hosts
127.0.0.1  https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/example
4.頁面使用
var self = this;
self.axios
    .post('/api/order_list')
    .then((response) => {
        console.log(response.data);
    });

12.axios二次封裝

1.assets/js/axios.js
import Axios from 'axios';
import qs from 'qs';
import {shim} from 'promise.prototype.finally';

shim();

let store = {};
const axios = Axios.create();
const requestMap = {};

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.interceptors.request.use((config) => {
    if (config.loading) {
        store.dispatch('open_loading', typeof config.loading === 'string' ? {msg: config.loading} : undefined);
    }

    if (config.mock) {
        config.adapter = (cfg) =>
            new Promise((resolve) => {
                setTimeout(
                    () =>
                        resolve({
                            data: config.mock,
                            status: 200,
                            statusText: 'mock ok',
                            config: cfg,
                            headers: '',
                        }),
                    cfg.mockTimeout || 0
                );
            });
    }

    config.cancelToken = config.cancelToken || Axios.CancelToken.source().token;

    if (config.successive) {
        const cancelToken = requestMap[config.url];
        if (cancelToken !== undefined) {
            cancelToken.reason = new Axios.Cancel('Canceled by successive request.');
        }
        requestMap[config.url] = config.cancelToken;
    } else if (config.single) {
        if (requestMap[config.url]) {
            config.cancelToken.reason = new Axios.Cancel('Canceled by singleton.');
        } else {
            requestMap[config.url] = config.cancelToken;
        }
    }

    if (config.method === 'post') {
        config.data = qs.stringify(config.data);
    }

    return config;
});

// Add a response interceptor
axios.interceptors.response.use(
    (response) => {
        if (response.config.loading) {
            store.dispatch('destroy_loading');
        }
        if (response.config.successive || response.config.single) {
            delete requestMap[response.config.url];
        }
        // Do something with response data
        let data = response.data;
        response.info = data.hasOwnProperty('info') ? data.info : data.msg;
        response.data = data.data;
        response.result = data.hasOwnProperty('result') ? data.result : data.code;

        return response;
    },
    (error) => {
        if (error.config) {
            if (error.config.successive) {
                if (requestMap[error.config.url] === error.config.cancelToken) {
                    delete requestMap[resp.config.url];
                }
            } else if (error.config.single) {
                delete requestMap[resp.config.url];
            }
            if (error.config.loading) {
                store.dispatch('destroy_loading');
            }
        }
        if (!Axios.isCancel(error)) {
            if (error.config && error.config.dialogError) {
                dialog.error();
            }
            try {
                console.log(JSON.stringify(error, null, 2));
            } catch (_err) {
                console.log(String(error));
            }
        }
        // Do something with response error
        return Promise.reject(error);
    }
);

axios.setStore = (_store) => (store = _store);

export default axios;
export const axiosPlugin = (Vue) => Object.defineProperty(Vue.prototype, '$axios', {value: axios, writable: true});

2.main.js
// import axios from 'axios' 這里請注意需要把之前引入的axios注釋掉,使用下面最新的封裝的axios
import axios, {axiosPlugin} from './assets/js/axios';
Vue.use(axiosPlugin);
3.使用axios
mounted () {
    var self = this;
    self.$axios
        .post('/api/order_list')
        .then((res) => {
            console.log(res.data);
        });
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 文/言生 周杰倫結(jié)婚了,又以光速生下女兒。 晚上我鼓搗著微博感嘆物是人非,時(shí)光飛速時(shí),接到一個(gè)電話。 一個(gè)陌生的號(hào)...
    言生閱讀 800評(píng)論 4 7
  • 生命中總會(huì)有那么一些人,他們以特定的形式出現(xiàn)在你生命里,頻繁出現(xiàn),久而久之成為一種習(xí)慣,甚至某些情況下會(huì)感到厭煩。...
    爽贏天下閱讀 300評(píng)論 0 0
  • 一 五一假日,氣溫回升。白天、藍(lán)云、陽光都顯示著夏日將來的標(biāo)志, 這是一個(gè)裙子飛揚(yáng)的季節(jié)。 昨天我決定在家把衣服...
    女公子99閱讀 601評(píng)論 0 5
  • 世間最好的默契,并非有人懂你的言外之意,而是有人懂你的欲言又止。 ??? 不久前在一篇文章中提到一個(gè)很有意思的解釋...
    分分兒閱讀 344評(píng)論 3 0

友情鏈接更多精彩內(nèi)容