云计算之VUE开发【上】

感情迁移 提交于 2020-01-01 00:01:53
0. 服务架构
    k8snode01   192.168.89.133  开发平台
    k8snode02   192.168.89.134  代码存放地 制品库
    k8smaster   192.168.89.132  线上平台 [URI: http://www.项目名.com,本地hosts文件可以解析一下]
1. VUE项目搭建流程:
    1. 安装node.js
    2. 安装npm , 使用npm 安装cnpm
        npm install -g cnpm --registry=https://registry.npm.taobao.org
    3. 安装 vue-cli
        cnpm install -g vue-cli
    4. 初始化项目
        vue init webpack todolist
    5. 安装相应的npm依赖
        cnpm install
    6. 修改项目监听地址
        vim config/index.js
            host: '192.168.89.133'
            port: 80
    7. 运行项目
        npm run dev
            Your application is running here: http://192.168.89.133:80
            占用当前终端
2. VUE项目部署升级

    vim /usr/local/bin/makeup
        #!/bin/bash
        #/usr/local/bin/makeup
        read -p 'service name:' servername

        if [ ! -d /backup/${servername} ];then
            mkdir /backup/${servername}
        fi
        cd /opt/vue-pros/${servername}/
        cnpm run build
        mv dist ${servername}
        zip -r ${servername}.zip ${servername}
        # 上传到制品库
        ssh k8snode02 ls /backup/${servername} &> /dev/null
        if [ $? -ne 0 ] ; then
            ssh k8snode02 mkdir -p /backup/${servername}
        fi
        scp ${servername}.zip k8snode02:/backup/${servername}/${servername}-`date +%Y%m%d-%H%M%S`.zip
        # 部署到服务器
        scp ${servername}.zip k8smaster:/usr/local/nginx/html/
        ssh k8smaster mv /usr/local/nginx/html/${servername} /tmp/${servername}-`date +%Y%m%d-%H%M%S`
        ssh k8smaster unzip /usr/local/nginx/html/${servername}.zip -d /usr/local/nginx/html
        ssh k8smaster rm -f /usr/local/nginx/html/${servername}.zip
        rm -rf ${servername} ${servername}.zip
        echo ${servername}"update finished"
    chmod +x /usr/local/bin/makeup
3. VUE中引入bootstrap,jquery
    安装依赖包
        cnpm install jquery --save-dev
        cnpm install popper.js --save-dev
        cnpm install bootstrap --save-dev
    vim main.js
        import 'bootstrap'
        import './assets/css/bootstrap.min.css'
        import './assets/css/bootstrap-reset.css'
        import './assets/css/assets/font-awesome/css/font-awesome.css'
        引入相关js,css文件

4. 配置路由
    https://segmentfault.com/a/1190000014441507?utm_source=tag-newest
    vim router/index.js
        ... ...
        const router = new Router({
          routes: [
            { path: '/login',   name: 'Login',        component: Login },
            { path: '/hello',  name: 'Hello',       component: Hello },
            { path: '/404', name: 'page404', component: Page404 },
            {
              path: '/',
              redirect: '/Login',
              component: Login
            },
            { path: '/base',       name: 'Base',       component: Base,
              children: [
                { path: 'filebeat',name: 'Filebeat',component: Filebeat },
                { path: 'baseline',name:"Baseline", component: Baseline },
                { path: 'deploy',name: 'Deploy', component: Deploy }
              ]
            },
            {
              path: '*',
              redirect: '/404',
              name: 'Page404',
              component: Page404
            },
          ]
        })
        export default router

5. 解决地址栏出现#问题
    1). vim index.html
        ... ...
        const router = new Router({
          mode: 'history',
        ... ...
    2). 修改nginx代理
        k8smaster[服务所在机器,在location下添加try_files]
        vim /usr/local/nginx/conf/conf.d/todolist.cnf
            server {
                    listen 80;
                    server_name     www.todolist.com;
                    location / {
                    try_files  $uri   $uri/  /index.html;
                            root   /usr/local/nginx/html/todolist;
                    index  index.html index.htm;
                    }
            }

6. Vue+django实现登录问题
    1). 安装axios
         cnpm install axio
    2). 修改main.js, 设置默认header
        ... ...
        import {setCookie,getCookie} from './assets/js/cookie'
        import axios from 'axios'
        Vue.prototype.$axios = axios;
        axios.defaults.headers.post["X-CSRFToken"] = getCookie("csrftoken");
        ... ...
    3). 编写cookie.js
        vim assets/js/cookie.js
            // 用export把方法暴露出来
            // 设置cookie
            export function setCookie(key,value) {
              var exdate = new Date(); //获取时间
              exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000);
              window.document.cookie = key + "=" + value + ";path=/;expires=" + exdate.toGMTString();
            }
            // 读取cookie
            export function getCookie(param) {
              var c_param = '';
              if (document.cookie.length > 0){
                var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
                for( var i=0;i<arr.length;i++){
                  var arr2 = arr[i].split('=');
                  if (arr2[0] === param){
                    c_param = arr2[1];
                  }
                }
                return c_param;
              }
            }

            // 删除cookie
            export function delCookie(key) {
              var exdate = new Date(); //获取时间
              exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000);
              window.document.cookie = key + "=" + '' + ";path=/;expires=" + exdate.toGMTString();
            }
    4). 修改 config/index.js , 给后端请求加前缀,以作区分
        proxyTable: {
          '/api': {
            target: 'http://192.168.89.133:80',
            changeOrigin: true,
            pathRewrite: {
              '^/api': '' // http://192.168.89.133:80/user/add 可以写成 '/api/user/add'
            }
          }
        },
    5). Login.vue页面配置
        a. 设置需要参数
            ... ...
            data = {
                username: '',
                userpass: '',
                csrfmiddlewaretoken: '',
            };
            ... ...
        b. 获得csrfmiddlewaretoken
            mounted () {
                var vm = this;
                  vm.$axios({
                    method: 'get',
                    baseURL: '/api',
                    url:'/accounts/login/',     // django默认登录页面
                  })
                  .then(function(response){
                    const regex = /csrfmiddlewaretoken' value='(.*)'/gm;
                    var arr, reg = new RegExp("csrfmiddlewaretoken' value='(.*)'");
                    if (arr === response.data.match(reg))
                      vm.form.csrfmiddlewaretoken = unescape(arr[1])
                    else
                      console.log('not found crsf value')
                  })
              },
        c. 提交登录信息
            login () {
                if( this.username === '' || this.userpass === ''){
                  alert('用户名或密码不能为空')
                }else {
                  var vm = this;
                  this.$axios({
                    method: 'post',
                    baseURL: '/api',
                    url: '/accounts/login/?next=/api/public/getuserinfo',
                    data: vm.data,
                    headers: {
                      'Content-Type': 'application/x-www-form-urlencoded'        //django 登录默认是form表单,需要添加
                    },
                    transformRequest: [  // django 登录默认是form表单,axios默认是json格式,说以发送数据要通过transformRequest转换为form格式
                      function (data) {
                        let ret = '';
                        for(let it in data){
                          ret += encodeURIComponent(it)+ '=' + encodeURIComponent(data[it]) + '&'
                        }
                        return ret
                      }
                    ]
                  }).then(function (response) {
                    if(response.data.code === 0){
                      setCookie('username',this.username);
                      window.location='/base';
                    }else {
                      vm.$message.error('Login failed!!');
                    }
                  });
                }

              }
    6. 简单路由校验配置
        vim route/index.js
              router.beforeEach(function (to, from , next) {
              console.log('to',to.name);
              function IsLogin() {
                console.log('login check....');
                if (getCookie('username') !== undefined){
                  return true
                }else {
                  return false
                }
              }
              if(IsLogin()){
                console.log('login true');
                if(to.name === 'login'){
                  next()
                }else {
                  next()
                }
              }else{
                console.log('login false');
                if(to.name === 'login'){
                  router.push({name: 'login'})
                }
              }
            });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!