公司项目须要用到nuxt.js的服务端渲染,因此使用了nuxt.js官方的脚手架搭建了项目,在这儿记录一些搭建过程当中踩过的坑。javascript
IE9是一个老大难的问题,由于它不支持ES6的语法,并且ie9也不知路由中的history模式,因此我在这儿暂时的解决办法以下。文档>>css
// nuxt.config.js
/* ** Global router middleware */
router: {
mode: 'history',
middleware: 'global',
fallback: true
},
复制代码
先在设置一下fallback,具体不知道为何看文档,最重要的是设置babel-polyfill。vue
yarn add babel-polyfill --dev
复制代码
// plugin 下 新建babel-polyfill文档下的index.js
import 'babel-polyfill'
复制代码
// nuxt.config.js
plugins: [
{ src: '@/plugins/babel-polyfill', ssr: true } // 将es6转换为es5 兼容ie9
],
复制代码
// 在文档根目录下新建 .babelrc 文件
{
"presets": [
[
"env",
{
"modules": false,
"useBuiltIns": "entry"
}
],
"stage-3"
]
}
复制代码
至此,项目就能在ie9上运行起来了,可能开发中还会有问题,到时候会进行补充。java
由于开发时项目使用的css预编译器是scss,因此注册全局的样式变量以下。node
先安装scss预编译器webpack
npm i node-sass sass-loader scss-loader --save-dev
复制代码
// nuxt.config.js 中配置 styleResources
css: [
{
src: '~/assets/styles/index.scss',
lang: 'scss'
}
],
modules: [
// Doc: https://axios.nuxtjs.org/usage
'@nuxtjs/axios',
'@nuxtjs/pwa',
'@nuxtjs/eslint-module',
'@nuxtjs/style-resources'
],
build: {
transpile: [/^element-ui/],
styleResources: {
scss: './assets/styles/variable/index.scss'
},
/* ** You can extend webpack config here */
extend(config, ctx) {}
}
复制代码
有时您但愿在整个应用程序中使用某个函数或属性值,此时,你须要将它们注入到Vue实例(客户端),context(服务器端)甚至 store(Vuex)。按照惯例,新增的属性或方法名使用$
做为前缀。ios
其实这个官方文档有,可是我仍是再写一遍加深一遍记忆。es6
好比说我想全局使用我定义的接口路径。web
// urls -> index.js (PS:必定要写在plugins文件目录下)
import Vue from 'vue'
import dev from './dev'
import prod from './prod'
// 判断是生产环境仍是开发环境
const env = process.env.NODE_ENV
const serverIp = env === 'production' ? prod.prodIp : dev.devIp
const interfacePORT =
env === 'production'
? `${prod.prodInterfacePort}${ prod.prodName === '' ? '' : '/' + prod.prodName }`
: `${dev.devInterfacePort}${dev.devName === '' ? '' : '/' + dev.devName}`
const serverUrl = 'http://' + serverIp + '/'
const interfaceUrl = 'http://' + serverIp + ':' + interfacePORT + '/'
// 同时注入context 和 Vue中,在Vue中会自动加上在前面加上$
export default ({ app }, inject) => {
inject('serverUrl', serverUrl)
inject('interfaceUrl', interfaceUrl)
}
复制代码
// nuxt.config.js
plugins: [
{ src: '@/config/url', ssr: false }, // 接口地址的全局引入
],
复制代码
而后就能够在项目中全局引入npm
export default {
mounted(){
console.log(this.$interfaceUrl)
}
asyncData(context){
console.log(context.app.$interfaceUrl)
}
}
复制代码
首先,先建立一个*.vue文件,个人文件名叫MyViewer.vue
,而后在全局注册这个组件,代码以下。
// 文件目录为 src/components/common/index.js
import MyViewer from './MyViewer'
const globalCom = function(Vue) {
if (globalCom.installed) return
globalCom.installed = true
Vue.component('MyViewer', MyViewer)
}
export default globalCom
复制代码
而后,在nuxt.js中的plugins文件目录下建立文件夹common-components
用于在nuxt.config.js中注册,代码以下。
// 文件目录为 src/plugins/common-components/index.js
import Vue from 'vue'
import globalCom from '@/components/common'
Vue.use(globalCom)
复制代码
最后,在nuxt.config.js中引用它,代码以下。
/* ** Plugins to load before mounting the App * 在这里注册插件 */
plugins: [
{ src: '@/plugins/common-components', ssr: false } // 引入全局公共组件
],
复制代码
先写这么多,之后随着项目进度继续更新。