用vue作項目的一些總結

原文連接:https://juejin.im/post/5b1e2b01f265da6e494def6b

1.新cli工具生成項目配置webpack,根路徑建立vue.conf.js

module.exports = {
    configureWebpack: config => {
        // 爲生產環境修改配置...if (process.env.NODE_ENV === 'production') {
            //html文件引入絕對地址
            config.output.publicPath = ''//不生成.map文件
            config.devtool = false;
        } else {
            // 爲開發環境修改配置...
            
        }
    }
}
複製代碼

2.npm run serve自動啓動用本地ip打開瀏覽器

"serve": "vue-cli-service serve --open --host 192.168.1.169"
複製代碼

window系統能夠在cmd裏面用ipconfig查看本地ip,而後直接把地址複製發送到手機,在手機上調試頁面,前提是手機和你電腦在一個網絡環境下css

3.移動端click點擊清除300ms延遲

import FastClick from'fastclick'window.addEventListener('load', () => {
    FastClick.attach(document.body)
})
複製代碼

在main.js引入代碼,而後頁面和組件均可以直接使用@click來綁定事件html

4.使用rem來寫移動端頁面

//main.js 引入依賴
import 'amfe-flexible'

//_base.scss 設計圖寬度除以10,假如設計圖寬度是750px那麼,基礎寬度就是75
$baseWidthSize: 75 !default;
@function to($px) {
    @return $px / $baseWidthSize * 1rem;
}

//組件和頁面使用; to()裏面的數值是photoshop裏測量的值
<style lang="scss">
    @import "../scss/_base.scss";
    .box{
        width: to(750);
        height: to(100);
    }
</style>
複製代碼

5.自定義指令上拉加載(div內滾動)

//main.js 引入import directive from'./directive'
directive(Vue)

//./directive/index.js import ScrollFix from'scrollfix'exportdefault (Vue) => {
    Vue.directive('scroll', {
        inserted: (el) => {
            new ScrollFix(el);
        }
    });

    Vue.directive('pull', {
        bind: (el, binding, vnode) => {
            if (!binding.value) {
                return;
            }
            let { self } = binding.value;
            el.addEventListener('scroll', utils.throttle(() => {
                let { scrollTop, offsetHeight, scrollHeight } = el;
                //整個列表的高度 - ( 滾動的高度 + 盒子的高度 )if ((scrollHeight - offsetHeight - scrollTop < 200) && self.isMore) {
                    self.isMore = false;
                    self.pullRequest && self.pullRequest();
                    console.log('上拉指令');
                }
            }), false);
        }
    });
}
複製代碼

這裏定義了2個指令 v-scroll用來處理ios div內滾動bug v-pull 用來作上拉加載vue

我習慣作div內滾動上拉加載,由於結合ScrollFix這個插件,在下拉頁面的時候能夠看不見此網頁由 192.168.1.169:8080 提供底色的背景;node

utils.throttle 是一個節流函數,utils是個對象我掛載到全局了,使用utils的地方多嫌import麻煩;webpack

在頁面中使用ios

<div class="done" v-scroll v-pull="self">
    …
</div>

export default {
    data() {
        return {
            data: [],
            page:1,
            self: this,
            isMore: true
        }
    },
    created(){
        this.pullRequest({page:1})
    },
    methods: {
        //上拉加載
        async pullRequest() {
            let { data } = await API.getList({ page: this.page });
            if(data.length == 0){
                this.isMore = false;
            }else{
                this.isMore = true;
                this.page ++;
            }
        }
    }
}
複製代碼

6.對請求函數的封裝

./api/server.jsweb

import'whatwg-fetch'import * as config from'@/config'functioncheckStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response
    } else {
        var error = newError(response.statusText)
        error.response = response
        throw error
    }
}

functionparseJSON(response) {
    return response.json()
}

exportdefault (url, params = {}, method = 'GET') => {
    returnnewPromise((resolve, reject) => {
        fetch(config.url + url, {
            method,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + (params.token || utils.getStorage('token'))
            },
            body: JSON.stringify(params)
        }).then(checkStatus)
            .then(parseJSON)
            .then((data) => {
               resolve(data);
            })
            .catch((err) => {
                reject(err)
            })
    })
}
複製代碼

請求用的fetch這個包,她能夠跨域請求數據vue-cli

對每一個請求函數的封裝 ./api/index.js; 在main.js中引入,而且把API對象掛載到了全局npm

import request from'./server'import config from'./api'let API = {};
for (let key in config) {
    let matchs = key.match(/^(\S+)\s*(.*)$/);
    API[`${matchs[1]}`] = async (params) => {
        returnawait request(config[key], params, matchs[2]);
    }
}
exportdefault API;
複製代碼

定義接口函數 key [ 方法名,請求類型 ] : 請求urljson

之後就在這個文件裏面加入請求函數,而且比較方便快捷

exportdefault {
    'login POST': 'user/login',
    'getDetails POST': 'user/getDetails',
    'getCaptcha POST': 'user/getCaptcha',
    'sendMsg POST': 'user/sendMsg',
    'verifyinfo POST': 'user/verifyinfo',
    'modifyPwd POST': 'user/modifyPwd',
}
複製代碼

頁面中使用

exportdefault {
    async created(){
        let { data } = await API.getDetails({ page: this.page });
    }
}
複製代碼

7. 設置不一樣路由下的頁面title ./utils/index.js

exportlet setTitle = (title) => {
    document.title = title
    var mobile = navigator.userAgent.toLowerCase()
    if (/iphone|ipad|ipod/.test(mobile)) {
        var iframe = document.createElement('iframe')
        iframe.style.visibility = 'hidden'// 替換成站標favicon路徑或者任意存在的較小的圖片便可
        iframe.setAttribute('src', '')
        var iframeCallback = function () {
            setTimeout(function () {
                iframe.removeEventListener('load', iframeCallback)
                document.body.removeChild(iframe)
            }, 0)
        }
        iframe.addEventListener('load', iframeCallback)
        document.body.appendChild(iframe)
    }
}
複製代碼

8. 使用新的vue-cli工具,使用yarn初始化項目報錯command failed: yarn

這時若是沒法解決又想切換回npm來安裝,能夠這樣作:

C:\Users\你的用戶名\ .vuerc 找到這個文件修改packageManager

packageManager: npm
複製代碼
相關文章
相關標籤/搜索