Nuxt 開發筆記總結

配置代理

yarn add @nuxtjs/axios 或者 npm install @nuxtjs/axiosvue

axios: {
    proxy: true
  },
  proxy: {
    '/api': 'http://api.example.com'
  },
 modules: ['@nuxtjs/axios']

組件中使用:http://api.example.com/test
```js
this.\(axios.\)get('/api/test').then(data => {
// todo
})
文檔ios

添加百度統計

在plugins目錄下建立tongji.js,內容以下:npm

if (process.BROWSER_BUILD && process.env.NODE_ENV === 'production') {
  var _hmt = _hmt || [];
  (function() {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?xxxx";
    hm.id = "baidu_tj";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
}

export default ({ app: { router }, store }) => {
  router.afterEach((to, from) => {
    var _hmt = _hmt || [];
    (function() {
      document.getElementById('baidu_tj') && document.getElementById('baidu_tj').remove();
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?xxxx";
      hm.id = "baidu_tj";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  })
}

id換成本身的,而後在nuxt.config,js中引入文件axios

開發spa應用

在nuxt.config.js中添加:api

mode: 'spa'

全局mixins

在plugins文件夾下添加mixins.jscookie

import Vue from 'vue'
Vue.mixin({
  methods: {
   getData(url, param = {}) {
      var self = this
      return new Promise(function (resolve, reject) {
        self.$axios({
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          // 啓用cookie
          withCredentials: true,
          data: param,
          params: param
        }).then((ret) => {
          const { data } = ret
          resolve(data)
        })
      })
    }
  }
})

全局組件

在plugins文件夾下添加components.jsapp

import Vue from 'vue'
import TopTip from '../components/top-tip.vue'

const components = { TopTip, }

Object.keys(components).forEach(key => {
  Vue.component(key, components[key])
})

全局過濾器

在plugins文件夾下添加filters.jspost

import Vue from 'vue'

export function formatDate(date, fmt) {
  let newDate = new Date(date)
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (newDate.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': newDate.getMonth() + 1,
    'd+': newDate.getDate(),
    'h+': newDate.getHours(),
    'm+': newDate.getMinutes(),
    's+': newDate.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}


const filters = { formatDate}

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

export default filters
相關文章
相關標籤/搜索