個人Vue之小功能統計

摘要:項目中常常會要用到大大小小的功能,因此我在這裏進行一個彙總,後面會持續添加至這篇博客,但願當你遇到這個功能時,個人博客可以對你有幫助,(上一篇博客說要在收假後寫一篇博客作一個年終總結,想了半天不知道寫什麼,文筆很差,就算了,不寫了,今天是情人節,祝沒有脫單的程序員趕快脫單,脫單了的永不脫髮,脫髮了的就當我沒說......)css

一.安裝(npm)html

圖片以下:可以使用npm進行安裝也可使用VSCode的終端進行安裝vue

1.安裝路由vue-routernode

npm install vue-router

2.安裝axiosios

npm install --save axios

3.安裝vuex程序員

npm install vuex --save

4.安裝scssweb

npm install --save-dev sass-loader
//sass-loader依賴於node-sass
npm install --save-dev node-sass

5.安裝element-uivue-router

npm i element-ui -S

6.main.js配置vuex

import Vue from 'vue'
import App from './App' import router from './router' import axios from 'axios' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import VueRouter from 'vue-router' import Vuex from 'vuex' Vue.use(ElementUI) Vue.use(VueRouter) Vue.use(Vuex) new Vue({ el: '#app', router, components: { App }, template: '<App/>', })

 

二.路由配置(index.js)npm

圖片以下(進行路由跳轉)

 

1.模塊概括

export default new Router({

  routes: [
    {
      path: '/', name: 'Login', component: Login, }, { path: '/Forget', name: 'Forget', component: Forget, }, { path: '/', component: Home, name: '用戶管理', children: [ { path: '/User', component: User, name: '用戶'}, { path: '/SeeEdit', component: SeeEdit, name: '用戶詳情'}, { path: '/Modify', component: Modify, name: '修改用戶資料'}, { path: '/changepsw', component: changepsw, name: '修改密碼'}, ] }, ...... ], })

 

2.路由切換後頁面滾動位置不變bug的解決方法

export default new Router({

  routes: [
      ......
  ],
  scrollBehavior (to, from, savedPosition) {
       // console.log(to) // to:要進入的目標路由對象,到哪裏去
       // console.log(from) // from:離開的路由對象,哪裏來
       // console.log(savedPosition) // savePosition:會記錄滾動條的座標
       if(savedPosition) { return savedPosition; }else{ return {x:0,y:0} } } })

 

 

三.儲存,傳值

1.Cookie

1.創建一個cookieUtil.js的文件

//設置cookie
export function setCookie(key,value) {
    var Days = 0.6; var exdate = new Date(); //獲取時間 exdate.setTime(exdate.getTime() + Days*24*60*60*1000); //保存的天數 //字符串拼接cookie 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; } }; function padLeftZero (str) { return ('00' + str).substr(str.length); };

 

2.在登陸界面login.vue引用這個js

//cookie
import {setCookie,getCookie}from '../router/cookieUtil'

 

3.而後儲存,取值

//儲存用戶信息
setCookie('sellerId', this.information.sellerId);
//取值用戶信息
this.sellerId = getCookie("sellerId");

 

4.退出登陸

<button @click="Signout">退出</button>
mounted () {
      this.sellerId = getCookie("sellerId"); if (this.sellerId==undefined||this.sellerId=="") { this.$router.push('/') } else { } }, methods: { //退出  Signout(){ setCookie("sellerId", "", -1); this.$router.push('/') }, }

 2.Session Storage

A頁面緩存aaa的值

sessionStorage.setItem('aaa', "111")

B頁面去獲取到值

alert(sessionStorage.getItem('aaa'))

3.經過路由帶參數進行傳值

A和B,A經過query把orderId傳遞給B

this.$router.push({ path: '/B', query: { orderId: 123 } }) // 跳轉到B

B獲取

let aaa=this.$route.query.orderId

 

 

 

四.發送驗證碼

圖片以下

1.html部分

<el-button :disabled="disabled" @click="sendcode" class="sendcode">{{btntxt}}</el-button>

2.js部分

export default {
        data() {
            return { disabled:false, time:0, btntxt:"發送驗證碼", }; }, methods: { //發送手機驗證碼倒計時  timer() { if (this.time > 0) { this.time--; this.btntxt=this.time+"s後從新獲取"; setTimeout(this.timer, 1000); } else{ this.time=0; this.btntxt="發送驗證碼"; this.disabled=false; } }, } }

 

五.div自適應屏幕寬高

1.像後臺管理系統那種格式,有頂部導航欄和左側導航欄,而切換的那一塊盒子怎麼能自適應屏幕的寬高減去頂部和左側固定的寬高呢?

html代碼:

<div v-bind:style="{width: myWidth,height: myHeight}"></div>

js代碼:

export default {

        data() {
            return { myWidth: (window.innerWidth - 240) + 'px', myHeight: (window.innerHeight - 100) + 'px', }; }, }

 

六.實時顯示當前時間

圖片以下(想後臺系統通常都會添加一個當前時間,方便用戶瞭解或記錄時間)

html代碼

<span class="time">{{nowTime}}</span>

js代碼

export default {

        data() {
            return { nowTime:"", nowWeek:"", }; }, // 建立完成時  created() { this.nowTimes(); }, methods: { //當前時間  timeFormate(timeStamp) { let year = new Date(timeStamp).getFullYear(); let month =new Date(timeStamp).getMonth() + 1 < 10? "0" + (new Date(timeStamp).getMonth() + 1): new Date(timeStamp).getMonth() + 1; let date =new Date(timeStamp).getDate() < 10? "0" + new Date(timeStamp).getDate(): new Date(timeStamp).getDate(); var week = timeStamp ? new Date(timeStamp) : new Date(); if(week.getDay() == 1){ this.nowWeek="週一" } else if(week.getDay() == 2){ this.nowWeek="週二" } else if(week.getDay() == 3){ this.nowWeek="週三" } else if(week.getDay() == 4){ this.nowWeek="週四" } else if(week.getDay() == 5){ this.nowWeek="週五" } else if(week.getDay() == 6){ this.nowWeek="週六" } else { this.nowWeek="週日" } let hh =new Date(timeStamp).getHours() < 10? "0" + new Date(timeStamp).getHours(): new Date(timeStamp).getHours(); let mm =new Date(timeStamp).getMinutes() < 10? "0" + new Date(timeStamp).getMinutes(): new Date(timeStamp).getMinutes(); this.nowTime = year + "/" + month + "/" + date +" "+ this.nowWeek +" "+ hh +":"+ mm ; // console.log(this.nowTime) clearInterval(this.Times); }, // 定時器函數  nowTimes(){ this.timeFormate(new Date()); this.Times=setInterval(this.nowTimes,1000); }, }, }

切記必定要清除定時器,當時做者忘記清除定時器頁面一直崩潰,後來打印才發現是忘記清除定時器了, 

 

七.自定義滾動列表

圖片以下

html代碼

<div class="right-select">
         <ul>
                 <li>張三1</li>
                 <li>張三2</li>
                 <li>張三3</li>
                 <li>張三4</li>
                 <li>張三5</li>
                 <li>張三6</li>
                 <li>張三7</li>
         </ul>
</div>

css代碼

    .right-select{
        width: 500px;
        height: 105px;
        overflow-y: scroll;
        border: 1px solid #bbbbbb;
        border-radius: 5px;
        margin-left: 65px;
    }
    .right-select::-webkit-scrollbar {
        width: 12px;
        background-color: #fff;
    }
    .right-select::-webkit-scrollbar-thumb {
        height: 26px;
        background-color: #666;
        border-radius: 50px;
    }

    .right-select::-moz-scrollbar {
        width: 12px;
        background-color: #fff;
    }
    .right-select::-moz-scrollbar-thumb {
        height: 26px;
        background-color: #666;
        border-radius: 50px;
    }

 自定義滾動條時,請記住要定義盒子的高度,否則滾動條會顯示不出來

 

八.判斷數據列表序號

圖片以下

html

<ul>
     <li  v-for="(item,index) in list" :key="item.id" >
          <p class="p1">{{ index+1>9?index+1:"0"+(index+1) }}</p>
          <p class="p2">{{ item.name }}&nbsp;&nbsp;{{ item.id }}&nbsp;&nbsp;{{ item.source }}</p>
     </li>
</ul>

 

js代碼

list: [{
     name: '張一', id: '1241', source: '經銷商', },{ name: '張二', id: '1242', source: '業務員', },{ name: '張三', id: '1243', source: '普通用戶', },{ name: '張四', id: '1244', source: '商城', }],

 

九.Form表單提交

html代碼

<form :model="reportForm">
        <input type="text" v-model="reportForm.name" placeholder="姓名"/>
        <input type="text" v-model="reportForm.sex" placeholder="性別"/>
        <input type="text" v-model="reportForm.age" placeholder="年齡"/>
</form>
<button @click="sub"></button>

js代碼

export default {
    data() {
        return { reportForm: { name: '', sex:'', age: '', } } }, methods: { sub() { let reportdata = this.reportForm; console.log(reportdata) } }
}

 

十.實現分頁效果

效果圖以下

 

該處是結合element-ui來寫的,請記得安裝element-ui,不知道安裝的請參考第一條

html代碼:

<template>
                 <table>
                       <thead>
                              <tr>
                                   <th class="sequence left-radius">序號</th>
                                   <th>姓名</th>
                                   <th>手機號</th>
                                   <th>性別</th>
                                   <th>用戶等級</th>
                                   <th>上級用戶</th>
                                   <th>建立日期</th>
                                   <th class="right-radius">操做</th>
                              </tr>
                       </thead>
                       <tbody>
                              <tr v-for="(item, index) in tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" :key="item.id">
                                   <td class="sequence">{{ index+1>9?index+1:"0"+(index+1) }}</td>
                                   <td>{{ item.name }}</td>
                                   <td>{{ item.phone }}</td>
                                   <td>{{ item.sex==1?"男":"女" }}</td>
                                   <td>{{ item.user }}</td>
                                   <td>{{ item.username }}</td>
                                   <td>{{ item.date }}</td>
                                   <td><a @click="See">查看</a><a @click="Edit">修改</a><a @click="Edit">刪除</a></td>
                              </tr>
                       </tbody>
                 </table>

           <div class="page">
                <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[5, 10, 20, 40]"
                      :page-size="pagesize"        
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="tableData.length">
                </el-pagination>
           </div>

</template>

 

js代碼:

<script>

     export default {
      data() {
        return {
          currentPage:1, //初始頁
          pagesize:10,//每頁的數據
          tableData: [{
            name: '張一',
            phone: '13111111111',
            sex: '1',
            user: '普通用戶',
            username: '李四',
            date: '2018/11/30'
          },{
            name: '張二',
            phone: '13122222222',
            sex: '0',
            user: '特殊用戶',
            username: '李四',
            date: '2018/12/30'
          },{
            name: '張三',
            phone: '13133333333',
            sex: '1',
            user: '普通用戶',
            username: '李四',
            date: '2018/11/30'
          },{
            name: '張四',
            phone: '13144444444',
            sex: '0',
            user: '普通用戶',
            username: '李四',
            date: '2018/11/30'
          },{
            name: '張五',
            phone: '13155555555',
            sex: '0',
            user: '特殊用戶',
            username: '李四',
            date: '2018/05/14'
          },{
            name: '張六',
            phone: '13166666666',
            sex: '1',
            user: '普通用戶',
            username: '李四',
            date: '2018/10/30'
          },{
            name: '張七',
            phone: '13177777777',
            sex: '1',
            user: '普通用戶',
            username: '李四',
            date: '2019/01/06'
          },{
            name: '張八',
            phone: '13188888888',
            sex: '1',
            user: '特殊用戶',
            username: '李四',
            date: '2018/06/17'
          },{
            name: '張九',
            phone: '13199999999',
            sex: '0',
            user: '普通用戶',
            username: '李四',
            date: '2018/09/25'
          },{
            name: '張十',
            phone: '13110101010',
            sex: '1',
            user: '特殊用戶',
            username: '李四',
            date: '2019/02/10'
          },{
            name: '張十一',
            phone: '13124683579',
            sex: '1',
            user: '特殊用戶',
            username: '李四',
            date: '2019/02/10'
          }]
        }
      },

      methods: {
            // 初始頁currentPage、初始每頁數據數pagesize和數據data
            handleSizeChange: function (size) {
              this.pagesize = size;
              console.log(this.pagesize)  //每頁下拉顯示數據
            },
            handleCurrentChange: function(currentPage){
              this.currentPage = currentPage;
              document.documentElement.scrollTop = 0;//點擊翻頁的時候回到頂部
              console.log(this.currentPage)  //點擊第幾頁
            },
      },
    }

</script>

 

css代碼:

//分頁
    /deep/.el-pagination{

      margin-bottom: 30px;
      float: right;
      font-size: 20px;
      color: #333333;
      margin-right: 55px;
      font-weight: normal;

    .el-select .el-input{
      width: 126px;
      height: 36px;
    }
    .el-select .el-input .el-input__inner{
      height: 100%;
      font-size: 20px;
      color: #333333;
    }
    .el-pagination__editor.el-input .el-input__inner{
        height: 36px;
    }
    .btn-prev,.btn-next{
      height: 36px;
    }
    .btn-prev{
      border-radius: 5px 0 0 5px;
    }
    .btn-next{
      border-radius: 0 5px 5px 0;
    }
    .el-pager li{
      line-height: 36px;
      height: 36px;
      font-size: 20px;
    }
    .el-pagination__total{
      color: #333333;
    }
     button,span:not([class*=suffix]){
      height: 36px;
      line-height: 36px;
      font-size: 20px;
      color: #333333;
    }
    .el-pagination__editor.el-input{
      font-size: 20px;
    }
  }

 

十一.懸浮改變圖片和文字顏色

圖片事例以下:

起始懸浮後

 

html代碼:

<div class="UserChoice-listtop">
        <div class="listonebtn" @mouseenter="enter1" @mouseleave="leave1">
                 <img :src="img1" />
                 <p>全部用戶</p>
        </div>
</div>

js代碼:

export default {
      data() {
        return {
            img1: require('../../images/alluser.png'),
        }
      },

      methods: {
            //懸浮切換圖片
            enter1: function(){
                this.img1 = require('../../images/alluser2.png');
            },
            leave1: function(){
                this.img1 = require('../../images/alluser.png');
            },
      },
    }

至於文字樣式改變的話,直接用css的:hover解決就好。

 

十二.單選按鈕控制模塊顯示隱藏

html以下:

<div class="attribute-radio" @change="btn">
         <el-radio v-model="radio" label="0"></el-radio>

<el-radio" v-model="radio" label="1"></el-radio>
</div> 

<div v-show="show"> <p>我出來了<p> </div>

js以下:

export default {
        data () {
            return {    
                radio:'0', 
                show:false,
            }
        }
        methods: {
            //選擇代理商屬性
            btn(){
                if(this.radio==="1"){
                    this.show=true;
                }else{
                    this.show=false;
                }
            },
         }
}

 

十三.搜索功能

1.點擊按鈕進行搜索

html代碼:

<!-- 搜索框加按鈕 -->
<el-input placeholder="請搜索關鍵詞" prefix-icon="el-icon-search" v-model="keyword"></el-input>
<el-button class="searchbtn" @click="search">搜索</el-button>
<!-- 數據 -->
<ul>
    <li v-for="(item,index) in agentlisttwo" :key="item.id" >
          <p class="p1">{{ index+1>9?index+1:"0"+(index+1) }}</p>
          <p>{{item.userID}}</p>
          <p>{{item.agentnum}}</p>
          <p>{{item.username}}</p>
          <p>{{item.phone}}</p>
    </li>
</ul>

js代碼:

<script>
    
    export default {
      data() {
        return {
            keyword:'',//搜索關鍵詞
            agentlisttwo:'',//搜索重定義數組
            agentlist: [{
                userID: "1240",
                agentnum: "22",
                username: "張無忌",
                phone: "13112345678",
            },{
                userID: "1241",
                agentnum: "23",
                username: "林平之",
                phone: "13114785236",
            },{
                userID: "1242",
                agentnum: "24",
                username: "令狐沖",
                phone: "13196584589",
            },{
                userID: "1243",
                agentnum: "25",
                username: "獨孤求敗",
                phone: "13115963256",
            },{
                userID: "1244",
                agentnum: "26",
                username: "包租婆",
                phone: "13110254523",
            },{
                userID: "1245",
                agentnum: "27",
                username: "韋小寶",
                phone: "13187455236",
            },{
                userID: "1246",
                agentnum: "28",
                username: "小燕子",
                phone: "13174552223",
            },{
                userID: "1247",
                agentnum: "29",
                username: "花無期",
                phone: "13174586358",
            }],   
        }
      },

      // 建立完成時
      created() {
           //重定義數組
           this.agentlisttwo =  this.agentlist;
      },

      methods: {

            search(){
                //搜索
                var keyword = this.keyword;
                if (keyword) {
                        this.agentlisttwo =  this.agentlist.filter(function(agentlist) {
                            return Object.keys(agentlist).some(function(key) {
                                return String(agentlist[key]).toLowerCase().indexOf(keyword) > -1
                            })
                        })
                }else{
                    this.agentlisttwo =  this.agentlist;
                }
            },
            
      },
    }

</script>

2.輸入框邊輸入邊搜索

html代碼:

<!-- 搜索框加按鈕 -->
<el-input placeholder="請搜索關鍵詞" prefix-icon="el-icon-search" v-model="keyword" v-on:input ="inputFunc"></el-input>
<!-- 數據 -->
<ul>
    <li v-for="(item,index) in agentlisttwo" :key="item.id" >
          <p class="p1">{{ index+1>9?index+1:"0"+(index+1) }}</p>
          <p>{{item.userID}}</p>
          <p>{{item.agentnum}}</p>
          <p>{{item.username}}</p>
          <p>{{item.phone}}</p>
    </li>
</ul>

js代碼:

<script>
    
    export default {
      data() {
        return {
            keyword:'',//搜索關鍵詞
            agentlisttwo:'',//搜索重定義數組
            agentlist: [{
                userID: "1240",
                agentnum: "22",
                username: "張無忌",
                phone: "13112345678",
            },{
                userID: "1241",
                agentnum: "23",
                username: "林平之",
                phone: "13114785236",
            },{
                userID: "1242",
                agentnum: "24",
                username: "令狐沖",
                phone: "13196584589",
            },{
                userID: "1243",
                agentnum: "25",
                username: "獨孤求敗",
                phone: "13115963256",
            },{
                userID: "1244",
                agentnum: "26",
                username: "包租婆",
                phone: "13110254523",
            },{
                userID: "1245",
                agentnum: "27",
                username: "韋小寶",
                phone: "13187455236",
            },{
                userID: "1246",
                agentnum: "28",
                username: "小燕子",
                phone: "13174552223",
            },{
                userID: "1247",
                agentnum: "29",
                username: "花無期",
                phone: "13174586358",
            }],   
        }
      },

      // 建立完成時
      created() {
           //重定義數組
           this.agentlisttwo =  this.agentlist;
      },

      methods: {

            inputFunc(){
                //搜索
                var keyword = this.keyword;
                if (keyword) {
                        this.agentlisttwo =  this.agentlist.filter(function(agentlist) {
                            return Object.keys(agentlist).some(function(key) {
                                return String(agentlist[key]).toLowerCase().indexOf(keyword) > -1
                            })
                        })
                }else{
                    this.agentlisttwo =  this.agentlist;
                }
            },
            
      },
    }

</script>

 或者html:

<el-input placeholder="請搜索關鍵詞" prefix-icon="el-icon-search" v-model="keyword"></el-input>

js:

      // 搜索關鍵字
      computed: {
            agentlisttwo: function() {
                var _keyword = this.keyword;
                if (_keyword) {
                    return this.agentlist.filter(function(product) {
                        return Object.keys(product).some(function(key) {
                            return String(product[key]).toLowerCase().indexOf(_keyword) > -1
                        })
                    })
                }
                return this.agentlist;
            }
       }

 

 

十四.點擊按鈕複製文字

html代碼:

<!-- 複製連接 -->
<div class="link-popup">
         <div class="link-popup-con">
                <div class="linkpopup-title">分享連接</div>
                 <p>{{address}}</p>
                 <el-button class="copyurl" @click="copylink">複製連接</el-button>
          </div>
 </div>

js代碼:

export default {
      data() {
        return {
             address:'https://www.baidu.com/',
        }
      },
      methods: {
            //複製連接
            copylink(){
                const input = document.createElement('input')
                document.body.appendChild(input)
                input.setAttribute('value',this.address)
                input.select()
                if (document.execCommand('copy')) {
                    document.execCommand('copy');
                }
                document.body.removeChild(input)
            },
      },
    }

 

十五.點擊按鈕下載圖片

html代碼:

<!-- 下載二維碼 -->
<div class="link-popup">
         <div class="link-popup-con">
                <div class="linkpopup-title">分享二維碼</div>
                <img :src="imgs" />
                 <el-button @click="downloadqrcode">下載二維碼</el-button>
         </div>
</div>

js代碼:

export default {
      data() {
        return {
             imgs:require("../../images/qrcode.png"),
        }
      },
      methods: {
            //下載二維碼
            downloadqrcode(){
                //必須同源才能下載
                var alink = document.createElement("a");
                alink.href = this.imgs;
                alink.download = "二維碼"; //圖片名
                alink.click();
                this.qrcodeshow=false;
            },
      },
    }

 

十六.input框禁止輸入負數和小數

html代碼:

<input type="number" @blur="handleInput($event,index)" v-model="num" />

 

js代碼:

//input框
handleInput(e,i) {
           let boolean = new RegExp("^[1-9][0-9]*$").test(e.target.value)
            if(!boolean){
                 this.$message.warning("請輸入正整數!")
                 this..num = '1'
            }
 },

 

十七.將表格裏面的數據導出Excel文件

1.安裝

npm install -S file-saver xlsx
npm install -D script-loader

2.引入兩個js文件

在page目錄下新建vendor文件夾,裏面放入Blob.js和Export2Excel.js兩個JS文件 

百度網盤地址:連接: https://pan.baidu.com/s/1W9eTSR3-WaT8s-cDspXt0Q 提取碼: 8wqc 

3.html和js

<el-button class="export" @click="exportExcel">導出Excel文件</el-button>
// 導出Excel
exportExcel(){
    require.ensure([], () => {        
        const { export_json_to_excel } = require('@/vendor/Export2Excel.js');  //引入文件      
        const tHeader = ['建立時間','訂單ID','訂單狀態','訂單金額','訂單備註']; //表頭
        const filterVal = ['time', 'OrderID','OrderState','money','remake'];//table表格中對應的屬性名(數據中的字段名)     
        const data = this.formatJson(filterVal, this.tableData); //表格綁定數據Cashdata轉json       
        export_json_to_excel(tHeader, data, '採購記錄');
        })
    },
        formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
},

 補充:咱們根據屬性名取值是在以數據在一層的基礎上,可是若是後臺返回的數據爲多層,那麼表格則取不到數據,數據爲空,咱們應該把數組從新定義一下,以下:

// 導出Excel
exportExcel(){
    require.ensure([], () => {        
        const { export_json_to_excel } = require('@/vendor/Export2Excel.js');  //引入文件      
        const tHeader = ['訂單ID','訂單金額','手機號']; //表頭
        const filterVal = ['orderId', 'totalPrice',"customerId"];//table表格中對應的屬性名(數據中的字段名)     
        const data = this.formatJson(filterVal, this.directdata); //表格綁定數據Cashdata轉json   
        var datatwo=[];
        var j=0;
        for(let i in data){
            datatwo[j++] = data[i][2].phone;
            data[i].splice(2,1)
            data[i].splice(2,0,datatwo[i])
        }  
        export_json_to_excel(tHeader, data, '下層業績');
    })
},

 

 

十八.axios請求get、post、put、delete方法的使用

1.get方法

axios({
    method:'get',
     url:this.API.requestuser+getCookie("ID")+'/',

}).then(response => {
     console.log(response.data)           
}).catch(err => {
     console.log(err);
})
axios({
    method:'get',
     url:this.API.requestuser,
     params:{
         id:getCookie("ID"),
    }
}).then(response => {
     console.log(response.data)           
}).catch(err => {
     console.log(err);
})

2.post方法

axios({
     method:'post',
     url:this.API.requestLogin,
     data:{
           username: this.inforForm2.userphone,
           password:this.inforForm2.password,
     }

}).then(response => {
      //獲取登陸信息
      // console.log(response);
                        
     }else{
           this.$message.error('登陸失敗!');
     }                     
}).catch(err => {
})

3.put方法

//開始上傳文件 新建一個formData
 let param = new FormData();
 param.append("oldPassWord", this.forgetForm2.password);
 //經過append向form對象添加數據
 param.append("newPassWord", this.forgetForm2.passwordtwo);

 //配置
 let config = {
      //添加請求頭 
      headers: {
              "Content-Type": "multipart/form-data",
              Authorization: "Bearer " + getCookie("token"),
      },

};
var id=getCookie("ID");
axios.put(this.API.requestPswtwo+id+'/', param, config).then(response =>{
        //獲取信息
        console.log(response);
        //判斷是否修改爲功進行跳轉
        alert("修改密碼成功")

}).catch(function (error) {
         alert("修改密碼失敗")
});

注意若是是添加數組:param.append("details", JSON.stringify(this.orderdata));

 

4.delete方法

let id=i;
axios({
        method:'delete',
        url:this.API.requeststockshop+id+'/',

}).then(response => {
        // console.log(response)  
        if(response.status===204){
              this.$message({
                     message: '刪除商品成功!',
                     type: 'success'
             });
             this.getshoplist()
         }      
}).catch(err => {
         console.log(err);
})

 

十九.解決vue項目首頁加載過慢的狀況

點擊f12,打開NetWork,咱們會看到app.js耗費了大量的時間,因此咱們須要把路由懶加載一下

import Login from '@/page/Login'
//把上面這種寫法換成下面這種寫法
const Login = r => require.ensure([], () => r(require('@/page/Login')), 'Login');

 

二十.rem的配置

pc端

打開main.js,把如下的代碼加入進去,而後換算比例爲1rem=100px

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  mounted() {
      setRem();
  }
})

// rem適配
function setRem() {
  var whdef = 100/1920;// 表示1920的設計圖,使用100PX的默認值
  var bodyWidth = document.body.clientWidth;// 當前窗口的寬度
  var rem = bodyWidth * whdef;// 以默認比例值乘以當前窗口寬度,獲得該寬度下的相應FONT-SIZE值
  document.getElementsByTagName('html')[0].style.fontSize = rem + 'px';
}
window.addEventListener('load', setRem);
window.addEventListener('resize', setRem);

 手機端

(function(doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function() {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
        };
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

 

 

 

二十一.根據接口返回的地址生成二維碼圖片

1.安裝qrcodejs2插件,在控制檯輸入:

npm install qrcodejs2 --save

2.在你運用的頁面裏面引入:

import QRCode from 'qrcodejs2'

3.頁面展現 :

html:寫入標籤

<div id="qrcode"></div>

js:配置,在methods方法裏配置:

qrcode () {
    let qrcode = new QRCode('qrcode',{
        width: 200, // 設置寬度,單位像素
        height: 200, // 設置高度,單位像素
        text: 'https://www.baidu.com' // 設置二維碼內容或跳轉地址
    })
}

而後,須要調用,若是是接口獲取的地址,則在接口裏面調用:

this.$nextTick(() => {
     this.qrcode()
})

 

二十二.下載pdf文件

//下載報告
downloadreport(fn){
    fetch('http://60.10.25.240/api/common/UEditorDownload?suburl=ueditor/upload/file/20180802/1533197094431007371.pdf').then(function(response) { 
        if (response.ok) {        
            return response.arrayBuffer();
        }    throw new Error('Network response was not ok.');
    }).then(function(arraybuffer) {    
        let blob = new Blob([arraybuffer], {        
            type: `application/pdf;charset-UTF-8` //word文檔爲msword,pdf文檔爲pdf
        });    
        let objectURL = URL.createObjectURL(blob);    
        let downEle = document.createElement("a");    
        let fname = `download`; //下載文件的名字
        downEle.href = objectURL;
        downEle.setAttribute("download", fname);    
        document.body.appendChild(downEle);
        downEle.click();
    }).catch(function(error) {    
        console.log('There has been a problem with your fetch operation: ', error.message);
    });
},

 

二十三.去掉地址欄的#符號

打開路由router文件夾裏面的index.js文件,改變hash模式

export default new Router({
  mode:'history',//默認是hash模式,去除#/
  routes: [
    {
  ......

此處須要後臺配合,後臺須要進行更改,不然上線後刷新頁面會爲404

 

 

 

 

還在持續更新中~,以爲有幫助的麻煩關注一下,謝謝!

相關文章
相關標籤/搜索