vue/搭建环境

326 阅读4分钟

1. 初始化项目

vue create 项目名称

2. 整理结构

router/store

3. 引入UI组件

vue add element 选择按需加载,安装完成后生产文件夹plugins/element.js

在入口文件main.js中也引入了plugins/element.js

babel.config.js中也注入了elememt

4. 添加网络请求axios+跨域

  1. npm install --save axios

    utils/http.js(见axios封装)

  2. api/base.js/index.js

  3. 跨域解决

     3.x版本
     vue cli/配置参考/devServer.proxy
     在根目录下配置vue.config.js
    
    2.x版本config/index.js
    proxyTable: {
      "/api": {
        target: "http://localhost:3000",
        pathRewrite: {
          '^/api': ''
        },
        changeOrigin: true
      }
    }
    

5. mock数据处理

1.express

npm install --save express
mock/index.js/router.js

2. 如果需要随机生成数据mock.js

npm install mockjs --save
var Mock=require('mockjs')

6. node.js+前后端合并

1.nodemon(nodejs-express修改后自动更新)

1.全局安装

npm install -g nodemon

项目安装

npm install --save-dev nodemon

2.配置nodemon.json

{
    "restartable": "rs",
    "ignore": [
        ".git",
        ".svn",
        "node_modules/**/node_modules"
    ],
    "verbose": true,
    "execMap": {
        "js": "node --harmony"
    },
    "watch": [],
    "env": {
        "NODE_ENV": "development"
    },
    "ext": "js json"
}

3.引入debug模块

var debug = require('debug')('my-application');
app.listen(3000, function () {
    debug('Express server listening on port ' + 3000);
});

4.运行

nodemon index.js

备注:直接进行1,4操作即可。

2.前后端合并运行

1.安装

npm install -g concurrently

2.配置文件package,.json/scripts

"nodemon": "nodemon mock/index.js",
"dev":"concurrently \"npm run serve\" \" nodemon mock/index.js \""

3.运行

npm run dev

7. vuex

8. token验证

导航守卫,路由跳转前 plugins/permission.js

import router from "./index"
import store from "../store"

// 定义导航守卫
router.beforeEach((to, from, next) => {
    if (to.matched.some(item => item.meta.isLogin)) {
        // 需要登陆:判断token是否存在
        const token = store.state.token;
        if (token) {
            next();
        } else {
            next({path: "/login",query:{from:to.fullpath})
        }
    } else {
        // 不需要登陆
        next();
    }
})

login.js

import storage from "../../utils/storages";
import { mapActions } from "vuex";
export default {
  name: "login",
  data() {
    return {
      username: "",
      password: ""
    };
  },
  methods: {
    ...mapActions(["getTokenAction"]),
    loginHandler() {
      this.$api.getLogin({
          username: this.username,
          password: this.password
        })
        .then(res => {
          this.getTokenAction(res.data.token);
          storage.setItem("token", res.data.token);
          if(this.$route.query.from){
              this.$router.push(this.$route.query.from)
          }else{
              this.$router.oush('/')
          }
        });
    }
  }
};

网络请求依赖于token:大部分的后台接口,为了数据安全,都会增加一个请求头,需要参数token

9. 指令(directives)和过滤器(service)

10. 加载第三方

echarts

安装

npm install echarts --save

使用地图时入口文件main.js(文件位置)引入

import "../node_modules/echarts/map/js/china.js"
import './plugins/echarts'

plugins/echarts.js

import echarts from 'echarts'
import Vue from 'vue'
// 将echarts挂在到vue实例对象上
const install = function (Vue) {
    // 双向数据绑定原理
    Object.defineProperties(Vue.prototype, {
        $charts: {
            get() {
                return {
                    line: function (id,data) {
                        // 初始化Echarts的操作
                        this.chart = echarts.init(document.getElementById(id));
                        this.chart.clear();
                        // 配置参数
                        var option = {
                            xAxis: {
                                type: 'category',
                                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [{
                                data: data,
                                type: 'line'
                            }]
                        };
                        // 设置参数
                        this.chart.setOption(option);
                    },
                    radar: function (id) {
                        // 初始化Echarts的操作
                        this.chart = echarts.init(document.getElementById(id));
                        this.chart.clear();

                        var option = {
                            backgroundColor: '#161627',
                            title: {
                                text: '雷达图'
                            },
                            tooltip: {
                                trigger: 'item'
                            },
                            radar: {                              //雷达图使用 radar 组件作为其坐标系
                                indicator: [                     //雷达图的指示器
                                    { name: '外观', max: 100 },
                                    { name: '拍照', max: 100 },
                                    { name: '系统', max: 100 },
                                    { name: '性能', max: 100 },
                                    { name: '屏幕', max: 100 }
                                ],
                                name: {                          //雷达图每个指示器名称的配置项。
                                    color: 'rgb(238, 197, 102)'
                                },
                                nameGap: 5,                       //指示器名称和指示器轴的距离。
                                splitLine: {                     //坐标轴在 grid 区域中的分隔线样式。
                                    lineStyle: {
                                        color: [
                                            'rgba(238, 197, 102, 0.2)', 'rgba(238, 197, 102, 0.3)',
                                            'rgba(238, 197, 102, 0.4)', 'rgba(238, 197, 102, 0.6)',
                                            'rgba(238, 197, 102, 0.8)', 'rgba(238, 197, 102, 1)'
                                        ].reverse()
                                    }
                                },
                                splitArea: {                     //不显示区域
                                    show: false
                                },
                                axisLine: {                     //刻度线样式
                                    lineStyle: {
                                        color: 'rgb(238, 197, 102)'
                                    }
                                },
                                shape: 'circle',                 //雷达图绘制类型  支持 'polygon''circle'
                                center: ['50%', '50%'],
                                radius: '80%',
                                startAngle: 90
                            },
                            series: [
                                {
                                    name: '雷达',
                                    type: 'radar',
                                    symbol: 'circle',            //标记的图形。
                                    itemStyle: {                //折线拐点标记的样式。
                                        normal: {
                                            color: '#B3E4A1'
                                        }
                                    },
                                    lineStyle: {                 //线条样式。
                                        normal: {
                                            type: 'dotted',
                                            width: 1,
                                            opacity: 0.8
                                        }
                                    },
                                    areaStyle: {                //区域填充样式。
                                        normal: {
                                            opacity: 0.8
                                        }
                                    },
                                    label: {                     //图形上的文本标签,可用于说明图形的一些数据信息
                                        normal: {
                                            show: false
                                        }
                                    },
                                    data: [
                                        {
                                            value: [85, 90, 90, 95, 95],
                                            name: '某手机'
                                        }
                                    ]
                                }
                            ]
                        };
                        // 设置参数
                        this.chart.setOption(option);
                    },
                    myMap: function (id) {
                        // 初始化Echarts的操作
                        this.chart = echarts.init(document.getElementById(id));
                        this.chart.clear();
                        var option = {
                            tooltip: {},
                            /*方法二 */
                            series: [{
                                name: '省',
                                type: 'map',
                                map: 'china',
                                roam: false,
                                zoom: 1.2,
                                aspectScale: 0.75,
                                label: {
                                    normal: {
                                        show: true,
                                        textStyle: {
                                            color: 'rgba(0,0,0,0.4)'
                                        }
                                    }
                                },
                                itemStyle: {
                                    normal: {
                                        areaColor: 'rgba(0,255,236,0.1)',
                                        borderColor: 'rgba(118,237,236,1)',
                                    },
                                    emphasis: {
                                        areaColor: 'rgba(118,237,236,0.8)',
                                        shadowOffsetX: 0,
                                        shadowOffsetY: 0,
                                        shadowBlur: 20,
                                        borderWidth: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }]
                        };
                        // 设置参数
                        this.chart.setOption(option);
                    }
                }
            }
        }
    })
}
export default {
    install
}
Vue.use({install})

ueditor编辑器

参考地址 github.com/HaoChuan942…

  1. 安装
npm i vue-ueditor-wrap
  1. 将下载的压缩包解压并重命名为 UEditor(只需要选择一个你需要的版本,比如 utf8-php),放入你项目的 static 目录下。(vue-cli 2.x);

    如果你使用的是 vue-cli 3.x,可以把 UEditor 文件夹放入项目的 public 目录下。

  2. main.js

import VueUeditorWrap from 'vue-ueditor-wrap'
  1. 注册组件

在 main.js 里将它注册为全局组件

Vue.component('vue-ueditor-wrap', VueUeditorWrap)
  1. 根据项目需求修改配置
<vue-ueditor-wrap v-model="msg" :config="myConfig"></vue-ueditor-wrap>

data () {
  return {
    msg: '<h2><img src="http://img.baidu.com/hi/jx2/j_0003.gif"/>Vue + UEditor + v-model双向绑定</h2>',
    myConfig: {
      // 编辑器不自动被内容撑高
      autoHeightEnabled: false,
      // 初始容器高度
      initialFrameHeight: 240,
      // 初始容器宽度
      initialFrameWidth: '100%',
      // 上传文件接口(这个地址是我为了方便各位体验文件上传功能搭建的临时接口,请勿在生产环境使用!!!)
      serverUrl: 'http://35.201.165.105:8000/controller.php',
      // UEditor 资源文件的存放路径,如果你使用的是 vue-cli 生成的项目,通常不需要设置该选项,vue-ueditor-wrap 会自动处理常见的情况,如果需要特殊配置,参考下方的常见问题2
      UEDITOR_HOME_URL: '/static/UEditor/'
    }
  }
}

Vue I18n

Vue.js 的国际化插件

安装

npm install vue-i18n --save

vue-cli 3.x

vue add i18n

模块系统中使用它,你必须通过 Vue.use() 明确地安装 vue-i18n

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)