美文网首页
vue项目搭建步骤vue-cli+webpack+axios+r

vue项目搭建步骤vue-cli+webpack+axios+r

作者: 马小帅mm | 来源:发表于2018-08-17 11:38 被阅读0次

前提是你已安装好node,以下步骤都是mac环境,window稍微有点区别,区别不大,不做描述

1.安装脚手架vue-cli

sudo npm install -g vue-cli
vue.jpeg

2.安装webpack

sudo npm install -g webpack

3.用webpack初始化项目,项目名称vueDemo

vue init webpack vueDemo

4.项目描述文件配置

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.启动项目

npm run dev

7.压缩构建项目

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标签上加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本地环境API代理设置和解决跨域

1.修改config下面的index.js的dev
proxyTable: {
  '/api': {
        target: 'https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/example',
        secure: false,// 如果是https接口,需要配置这个参数??不确定是否需要
        changeOrigin: true,// 是否跨域
        pathRewrite: {
            '^/api': '',
        },
    }
},
2.重新构建项目
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);
        });
}

相关文章

网友评论

      本文标题:vue项目搭建步骤vue-cli+webpack+axios+r

      本文链接:https://www.haomeiwen.com/subject/beezbftx.html