Vue入坑筆記

近段時間常使用vue-cli開發,寫點記錄,避免時間久之忘了。css

環境

1. nodejs
  vue-cli開發基於nodejs環境,確保開發的環境中已安裝了nodejs。
  安裝教程 https://www.runoob.com/nodejs...
  查看是否已安裝nodejs,在cmd中輸入 node --version 若已安裝則輸出版本號。html

2. vue
  安裝vue環境 npm install vue
  安裝vue-cli環境,npm install --global vue-clivue

新建項目

1. 新建模板
  新建一個projectname的項目 vue init webpack projectname
  以後會出現Project name和Project description之類的,可有可無,能夠修改,也能夠默認跳過。
  是否安裝路由 ?Install vue-router?(Y/n) Y //看狀況定,通常都有用到
  初始化項目完畢,根據提示操做,模塊安裝完後便可啓動項目 npm run devnode

2. 修改配置
  安裝的模板有些配置通常狀況不符合本身須要,須要手動作些修改。
  build文件夾utils.js文件中設置 publicPath: '../../' 解決圖片路徑找不到的問題
  config文件夾的index.js文件build對象下的 assetsPublicPath: './' 解決打包後的項目頁面空白問題webpack

3. 安裝模塊
  使用模塊配合開發,如 Vue + Vuex + elementUI + axios + font-awesome + scssios

  • Scss

  安裝 Scss,使用方式 <style scoped lang="scss">
  npm install node-sass --save-dev
  npm install sass-loader --save-dev
  安裝 font-awesome,使用方式 <i class="fa fa-coffee"></i>
  npm install font-awesome --save main.js中引入 import 'font-awesome/css/font-awesome.css'
  git

  • elementUI

  安裝 elementUI,使用方式 <el-switch v-model="value"></el-switch>
  npm i element-ui -S
  在main.js中引入
  import Element from 'element-ui'
  import 'element-ui/lib/theme-chalk/index.css'
  Vue.use(Element, {size: 'small'})web

  • axios

  安裝axios,使用方式 this.$http(method:'post', url:'/webApi', data:{}).then(res=>{……});
  npm install axios -S
  在main.js中引入
  import axios from 'axios'
  Vue.prototype.$http = axiosvue-router

  • Vuex

  安裝Vuex,使用方式 this.$store.commit('setMsg','message');
  npm install vuex -S
  在src中新建文件夾vuex,在vuex文件夾中新建store.js,如vuex

//store.js
    import Vuex from 'vuex'
    import Vue from 'vue'
    Vue.use(Vuex)
    //定義狀態和暴露狀態,如
    const store = new Vuex.Store({
      state: {
        msg: 'message',
      },
      mutations: {
        setMsg(state, val) {
          state.msg = val
        },  
      }
    })
    export default store
    
    //main.js中引入
    import store from './vuex/store.js'
    
    new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>'
    })

發佈vue組件到npm

1. 新建項目
  使用cli快速搭建一個項目,和新建一個普通的項目同樣。假定項目爲項目名 projectname

2. 開發組件
  新建一個即將發佈的組件vue文件,好比在components目錄下新建componentname.vue

3. 修改配置文件

//修改package.json文件,如
{
  "name": "projectname", //發佈的包名,避免和已發佈的包名衝突
  "version": "1.0.0", //版本號,當第二次發佈時需手動設置其版本
  "description": "A Vue.js project", //項目的描述,可不寫
  "author": "starrysky", //項目的做者
  "private": false, //開源,非私有
  "main": "dist/componentname.min.js", //打包的入口文件
  "repository": { //倉庫地址,可不寫
    "type": "git",
    "url": ""
  },
}

//修改build文件夾中的webpack-prod.conf.js,如
  output: { //該部分爲重寫
    path: config.build.assetsRoot,
    publicPath: config.build.assetsPublicPath,
    filename: 'componentname.min.js',
    library: 'componentname',
    libraryTarget: 'umd'
  },
  plugins: [ //該部分刪減內容
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      allChunks: true,
    }),
    new OptimizeCSSPlugin(),
  ]
  
//修改config文件夾下index.js的build字段中的 assetsSubDirectory: '/'
//修改main.js文件
import componentname from '@/components/componentname.vue',
export default componentname

4. 打包項目
  進入項目終端,執行 npm run build
  打包後將.gitignore文件的dist/刪掉

5. 發佈模塊
  終端中登陸npm,npm login
  輸入帳號密碼後,執行發佈 npm publish

6. 使用模塊

//新項目中安裝npm包,npm install --save-dev projectname
import componetName from 'projectname'

components:{
  componetName
}

碰到的問題

1. 啓動服務失敗,非程序語法問題,致使啓動服務打包錯誤?
  多是node_modules版本與本機安裝的webpack版本不一致,刪除,執行npm install從新下載全部依賴,偶爾神奇的牆會致使安裝出錯,多試幾回。

2. 開發過程當中設置局域網可訪問?
  在config文件夾下的index.js中修改host字段值爲本機在局域網中的ip。

3. 開發過程當中跨域訪問?

//在config文件夾下的index.js中修改proxyTable,如跨域訪問 http:192.168.0.3:10010/api……
proxyTable: {
  '/api':{
   target: 'http:192.168.0.3:10010',
   chageOrigin: true,
   pathRewrite:{
     '^/api': '/api'
   }
  }
}

4. 項目打包後,頁面顯示空白?
  在config文件夾下的index.js中的build對象下設置 assetsPublicPath: './'

5. 項目打包後,圖片路徑加載錯誤?
  在build文件夾下的utils.js設置 publicPath: '../../'

6. 發出的請求編碼失敗?
  存在特殊字符致使編碼失敗,如%,對參數進行encodeURI編碼,替換瀏覽器的自動編碼。

7. class 繼承報錯 Class constructor xxx cannot be invoked without 'new' ?
  多是文件路徑問題。當class和繼承的class不一樣時在src文件夾內外的話,會出現該錯誤。

8. 使用elementUI時發現el-input類型爲number時,綁定的值爲0不顯示?
  elementUI版本2.3.4的bug,更新npm包便可。

9. 如何更新安裝的npm包?

npm install -g npm-check-updates //安裝高效升級插件
ncu //列出全部可更新的模塊
ncu -a //更新全部模塊

10. npm包發佈失敗,403無權限發佈?
  多半緣由是包名衝突,在發佈以前先查找是否已存在該模塊

11. axios請求,如何取消重複請求?

//axios請求攔截器中統一處理
let pending = []; //聲明一個數組用於存儲每一個請求的取消函數和標識
let cancelToken = axios.CancelToken;
let removePending = (config) => {
  let i = pending.findIndex(item => item.u === config.url+'&'+config.data);
  if(i > -1){ //執行取消操做並從刪除該條記錄
    pending[i].f();
    pending.splice(i, 1); 
  }
}

// http請求攔截器
axios.interceptors.request.use(config => {
  //統一get請求和post請求,並將其格式化
  removePending(config);
  config.cancelToken = new cancelToken((c)=>{ 
    pending.push({ u: config.url + '&' + config.data, f: c }); 
  }); 
  return config
}, error => {
  return Promise.reject(error)
})

// http響應攔截器
axios.interceptors.response.use(data => {
  removePending(data.config);
  return data;
}, error => {
  return Promise.reject(data:{})
})
相關文章
相關標籤/搜索