标签Vue

Nuxt.js

基于Vue2,支持Vue Router,Vuex,Vue Server Renderer(spa),Vue-meta

https://zh.nuxtjs.org/
https://www.nuxtjs.cn/

1,模版安装
https://github.com/nuxt-community/koa-template
vue init nuxt-community/koa-template <project-name>
cd <project-name> # move to your project
需将nuxt降级到1.4.2
npm install # or yarn install*[see note below]

npm i eslint-plugin-html@^3

2.脚手架安装
npm install -g npx
(npx在NPM版本5.2.0默认安装了):
$ npx create-nuxt-app <项目名>

rendering mode :Universal ->否开启SSR服务端渲染

$ cd <project-name>
$ npm run dev 运行开发模式

npm run build 打包构建
npm start 正式运行

npm install --update-binary 重新编译

问题一:使用ES6的 import/export,不支持import需使用babel

解决方案:
    1 在启动参数中加上  --exec babel-node
    2 在根目录下增加.babelrc配制文件
    {
        "presets":["es2015"]
    }
    3 npm install babel-preset-es2015
    npm install babel-cli -S

    deprecated babel-preset-es2015@6.24.1: ????  Thanks for using Babel: we recommend using babel-preset-env now: please read https://babeljs.io/env to update!
+ babel-preset-es2015@6.24.1
failed to start process, "babel-node" exec not found

Module build failed:Error:Plugin/Preset files are not allowed to export objects
1 删除    npm uninstall –save babel-loader
npm uninstall –save @babel/core
    2 新安装    npm install –save -dev babel-loader@^7

问题二:安装 sass

安装依赖
 "fibers": "^4.0.2","sass": "^1.26.3"
Windows + OS X instructions here: https://github.com/nodejs/node-gyp
Ubuntu users please run: `sudo apt-get install g++ build-essential`
RHEL users please run: `yum install gcc-c++` and `yum groupinstall 'Development Tools'`
Alpine users please run: `sudo apk add python make g++`
OS
xcode-select --install
后出现错误
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
解决办法:
1.使用softwareupdate --list查看可用的内容,然后softwareupdate --install -a安装所有更新或softwareupdate --install <product name>只安装Xcode更新。

2.$ rm -rf /Library/Developer/CommandLineTools
$ xcode-select --install

3. Apple 官网下载最新版本的Command Line Tools安装即可
https://developer.apple.com/download/more/
通过brew config查看当前CLT版本号是否变更
CLT: 1103.0.32.62 -> 11.5.0.0.1.1588476445
Xcode: 11.4


npm install  sass fibers

This relative module was not found:
** npm install sass-loader node-sass**
安装后可以会有提示:
npm WARN acorn-jsx@5.0.0 requires a peer of acorn@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN eslint-plugin-vue@4.7.1 requires a peer of eslint@^3.18.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

此时,需要安装:
$ npm i eslint@^3.18.0
$ npm i acorn@^6.0.0
3. 修改 nuxt.config.js
css: [
    'element-ui/lib/theme-chalk/reset.css',
    'element-ui/lib/theme-chalk/index.css'
],
...
build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    },
    cache: true
}

配置sass编译 lang="scss"
yarn add @nuxtjs/style-resources node-sass sass-loader
nuxt.config.js文件添加代码
   modules: [
        '@nuxtjs/style-resources'
    ],

Module build failed (from ./node_modules/eslint-loader/index.js): friendly-errors 23:51:12
TypeError: Cannot read property ‘eslint’ of undefined
at Object.module.exports (/Users/sweet/Desktop/IDEA_project/vue/nuxt/node_modules/eslint-loader/index.js:148:18)

解决方案:
1     npm install eslint-loader@2.1.2 –save -dev
最后再次执行就没问题了。
初始化的版本太旧,升级
“backpack-core”: “^0.8.4”,
“eslint”: “^3.19.0”,
“eslint-config-standard”: “^10.2.1”,
“eslint-loader”: “^2.1.1”,

常用组件

npm i koa-router
npm install --save axios
npm i -g webpack webpack-cli

数据渲染

 async mounted() {
      // mounted在服务端渲染时不会被执行,页面源码不会渲染有数据,只会在浏览器中发生效果
      // let self = this
      // let {status, data: { list }} = await axios.get('/city/list')
      // if (status === 200) {
      //   self.list = list
      // }
    },
    async asyncData() {
      let {status, data: { list }} = await axios.get('http://localhost:3000/city/list')
      if (status === 200) {
        return { list }
      }
    }

fetch 用于vuex

报错Error:Interface ‘NuxtApp’ incorrectly extends interface ‘Vue’

https://github.com/nuxt/typescript/issues/49 类似,element-ui的$loading和nuxt.js 中的$loading冲突导致,临时解决方法

tsconfig.json
"compilerOptions": {
    "skipLibCheck": true
}

配置请求的baseUrl参数

    nuxt.config.js文件添加代码
   env: {
        baseUrl: process.env.NODE_ENV == 'development' ? 'http://localhost:3000/mapi' : 'http://www.ddd.cn'
    }
    测试 test.js 文件
    任何文件都可以使用 process.env.baseUrl
import Http from '@/plugins/http/index'; // 封装axios请求
let API = process.env.baseUrl;
     // 文章列表
    getArticleList(params = {}) {
        let url = `${API}/api/article/weblist`;
        return Http.get(url, params)
    },

Window 或 Document 对象未定义?

npm install --save window
那个js文件有window就在那个文件添加一下代码
// 客户端
if (process.client) {
...your code
}
// 浏览器
if (process.browser) {
...your code
}
例子: 以wowjs为例子
if (process.browser) {
var { WOW } = require("wowjs");
}
if (process.browser) {
let wow = new WOW({
live: false
});
wow.init();
}
or
在webpack.base.config.js下的output中添加一条globalObject: 'this'
or
(function(window) {
/* Keep source code the same */
// })(typeof window == "undefined" ? global : window);
// or
})(this);
nuxt.js.config
plugins: [
'@/plugins/element-ui',
// '@/plugins/adapter-latest',
{src: '@/plugins/adapter-latest', ssr: false}
],

Vue调试神器vue-devtools

vue-devtools是一款基于chrome游览器的插件,用于调试vue应用,这可以极大地提高我们的调试效率。接下来我们就介绍一下vue-devtools的安装。

chrome商店直接安装
vue-devtools可以从chrome商店直接下载安装,非常简单,这里就不过多介绍了。不过要注意的一点就是,需要翻墙才能下载。

手动安装

第一步:找到vue-devtools的github项目,并将其clone到本地. vue-devtools
git clone https://github.com/vuejs/vue-devtools.git
第二步:安装项目所需要的npm包
npm install //如果太慢的话,可以安装一个cnpm, 然后命令换成 cnpm install
第三步:编译项目文件
npm run build
第四步:添加至chrome游览器
游览器输入地址“chrome://extensions/”进入扩展程序页面,点击“加载已解压的扩展程序…”按钮,选择vue-devtools>shells下的chrome文件夹。

还附上了一个.crx文件,在chrome拓展程序页面上把文件拖进去即可安装。

链接:https://pan.baidu.com/s/139hspAnspD7bJbo81xigmg 密码:1hsv

Vue中使用excel导出

<!-- 导入需要的包 (一定要放到head标签里)-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.1/xlsx.full.min.js"></script>

cnpm install -S file-saver xlsx

import FileSaver from “file-saver”;
import XLSX from “xlsx”;

table标签el-table上加一个id:如outTable,对应下面的exportExcel方法中的 document.querySelector(‘#outTable‘)

exportExcel() {
      var xlsxParam = { raw: true };//转换成excel时,使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

Vue 项目中使用 echarts

官网

第一种方法,直接引入echarts
安装echarts项目依赖
npm install echarts –save

//或者
npm install echarts -S

//var echarts = require(‘echarts’); //单个引用

全局引入
我们安装完成之后,可以在 main.js 中全局引入 echarts
import echarts from “echarts”;
Vue.prototype.$echarts = echarts;

创建图表
<template>
  <div id="app">
    <div id="main" style="width: 600px;height:400px;"></div>
  </div>
</template>
<script>
export default {
  name: "app",
  methods: {
    drawChart() {
      // 基于准备好的dom,初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("main"));
      // 指定图表的配置项和数据
      let option = {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: ["销量"]
        },
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    }
  },
  mounted() {
    this.drawChart();
  }
};
</script>
问题:
在以上例子中,我们获取dom的方式是通过document.getElementById('main'),也就是元素的id获取到dom的,这其实是会出现问题的。
代码如下
<div id="main"></div>
this.$echarts.init(document.getElementById('main'))
因为vue是单页面应用,如果将以上的组件使用两次,一个页面内id是不允许相同的,就会出现第一个组件正常显示,第二个组件无法显示。
解决办法:
在vue中,我们可以通过另一种方式获取dom,vue有一个$refs的对象,只要将组件注册ref。
代码如下
<div ref="main"></div>
this.$echarts.init(this.$refs.main)
或
this.$echarts.init(this.$refs['main'])
通过以上方法获取dom,无论组件复用多少次,都不需要担心id唯一的问题了。

第二种方法,使用 Vue-ECharts 组件
安装组件
npm install vue-echarts -S

使用组件
<template>
  <div id="app">
    <v-chart class="my-chart" :options="bar"/>
  </div>
</template>
<script>
import ECharts from "vue-echarts/components/ECharts";
import "echarts/lib/chart/bar";
//按需引入
import "echarts/lib/chart/line";
import "echarts/lib/chart/pie";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/legend";
import "echarts/lib/component/markPoint";
import "echarts/lib/component/markLine";
import "echarts/lib/component/graphic";

export default {
  name: "App",
  components: {
    "v-chart": ECharts
  },
  data: function() {
    return {
      bar: {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: ["销量"]
        },
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      }
    };
  }
};
</script>
<style>
.my-chart {
  width: 800px;
  height: 500px;
}
</style>
用 npm 与 Vue Loader 基于 ES Module 引入(推荐用法)用 npm 与 Vue Loader 基于 ES Module 引入(推荐用法)

import Vue from ‘vue’
import ECharts from ‘vue-echarts’ // 在 webpack 环境下指向 components/ECharts.vue

// 手动引入 ECharts 各模块来减小打包体积
import ‘echarts/lib/chart/bar’
import ‘echarts/lib/component/tooltip’

// 如果需要配合 ECharts 扩展使用,只需要直接引入扩展包即可
// 以 ECharts-GL 为例:
// 需要安装依赖:npm install –save echarts-gl,并添加如下引用
import ‘echarts-gl’

// 注册组件后即可使用
Vue.component(‘v-chart’, ECharts)

图表主题颜色的修改
echarts中有三种常见主题类型: default, light, dark,读者没有太大的颜色要求的话,可以直接修改theme。
示例如下:

<v-chart :options="barOptions" autoresize theme="light"></v-chart>
柱状图颜色的修改可以在options参数中直接添加color数组,如下示例:
options:{
    ...
    color: ["#64CDF0", "#F5686F"],
    ...
}
另外可参考官方示例,直接添加theme.json文件。
`````
2.XY轴体颜色和文本颜色修改
x轴的样式修改可以在xAxis配置参数中进行设置,y轴在yAxis中进行配置,可以修改轴线的颜色,文本的颜色大小,图标内分割线的颜色等

options: {

xAxis: [
{
type: “category”,
data: [“1月”,”2月”,”3月”,”4月”,”5月”,”6月”,”7月”,”8月”,”9月”,”10月”,”11月”,”12月”],
// 修改文本的颜色
axisLabel: {
color: “#BB3137”,
fontSize: 10
},
// 修改轴线的颜色
axisLine: {
lineStyle: {
color: “#BB3137”
}
}
}
],
yAxis: [
{
type: “value”,
axisLabel: {
color: “#BB3137”,
fontSize: 10
},
// 修改y轴横向分割线的颜色
splitLine: {
lineStyle: {
color: [“#FFC9CB”]
}
},
axisLine: {
lineStyle: {
color: “#BB3137”
}
}
}
],

}

横向柱状图的显示
在配置xAxis和yAxis的时候,第一个参数就是type,这个参数用于说明该轴的类型,当x的type为value,y的type为category的时候,柱状图就会显示成横向柱状图。
过滤xy轴文本内容
上图二中,如果没有做任何处理,x轴会显示20000,40000…这种类型,这样显示内容较长,不太友好,那么怎么改成上述那种显示呢?
xy轴文本的配置项中,都有formatter这一配置项,直接在这里进行修改就可以,示例如下:

xAxis: [
{
type: “value”,
axisLabel: {
fontSize: 10,
formatter: function(value, index) {
return parseInt(value / 10000) + “万”;
}
}
}
],

Y轴文本显示在轴线内
刻度标签默认是显示在刻度线左侧,如果想要显示在右侧,需要将inside设置为true即可,当进行此设置后,刻度标签可能会被柱状图覆盖掉,这时候,还需要设置zlevel,示例如下:
        inverse: true,
        axisLabel: {
          fontSize: 10,
          inside: true,
          interval: 0
        },
        zlevel: 1
inverse是用来显示是否翻转刻度线上的内容,即默认从上往下是321显示,如果你不想这样显示,将inverse设为true,就会按照123方式显示。
6.在柱状条头部添加标签内容
在series中添加label标签即可,可以在此标签内进行文本内容的颜色,位置,内容等的设置,如下示例:

series: [
{
name: “直接访问”,
type: “bar”,
barWidth: “40%”,
label: {
show: true,
position: “right”,
color: “#3D383A”,
formatter: “¥{c}”
},
data: [28540, 33534, 9390, 80330, 37220]
}
]

自定义图例修改
如上图所示,我想要自定义设置图例中的文本内容,让图例文本可以换行显示,并且大小颜色可以任意设置,这该如何设置呢?
虽然样式显示并不复杂,但是想在echarts中实现,却是有些麻烦,formatter支持函数自定义修改,我们可以通过此方法来进行设置,将想要显示的内容数据设置成全局变量,然后在此方法中进行操作修改,所有的设置均在legend参数中进行配置。
默认的图例是个方形,如果想要改成圆形,可以将icon设置成circle,即可将图例设置成原型,大小可以通过itemWidth和itemHeight来设置。
示例如下:

legend: {
icon: “circle”, // 将图例设置成原型
bottom: 0,
left: “center”,
itemWidth: 10,
itemHeight: 10,
// itemGap: 10,
formatter: name => {
let data = pieData; // 全局变量
let value = “”;
let price = “”;
for (let i = 0; i < data.length; i++) {
if (data[i].name == name) {
value = data[i].value;
price = data[i].price;
}
}
let arr = [
“{a|” + name + ” ” + value + “%}”,
“{b|¥” + price + “}”
];
return arr.join(“\n”);
},
textStyle: {
rich: {
a: {
fontSize: 12,
width: 100,
align: “left”
},
b: {
width: 100,
fontSize: 14,
align: “left”,
lineHeight: 20,
padding: [0, 0, 5, 0]
}
}
},
data: [“一季度”, “二季度”, “三季度”, “四季度”]
},
var pieData = [
{ value: 28, name: “一季度”, price: 108626.0 },
{ value: 24, name: “二季度”, price: 93108.0 },
{ value: 19, name: “三季度”, price: 73710.0 },
{ value: 29, name: “四季度”, price: 112506.0 }
];

环比图中间显示内容
官方示例中并没有给出环比图中间显示自定义图文的内示例,有个示例是,点击圆环内容,中间显示点击区域对应的内容名称,这个太过简单,并不能满足自定义中间区域图文的要求,想要实现这种要求,就需要用到graphic,在使用时需要单独引用出来,否则会报错,这是一个原生图形元素组件支持image,text,circle等元素。
使用示例如下:

options: {

graphic: {
type: “group”,
top: “middle”,
left: “center”,
height: 80,
children: [
{
type: “text”,
left: “center”,
top: “30%”,
style: {
text: “全年总业绩”,
textAlign: “center”,
textVerticaAlign: “middle”,
fill: “#999”,
font: “15px ‘Helvetica’,sans-serif”
}
},
{
type: “text”,
top: “60%”,
left: “center”,
position: [0, 10],
style: {
text: “9912322.00”,
textAlign: “center”,
textVerticaAlign: “middle”,
fill: “#3d383a”,
font: “22px ‘Helvetica’,sans-serif”
}
}
]
},

}
““

Vue.js

Vue官网
Vue CLI
Vue中文
Vue CLI 中文
Vue.js 教程
Webpack打包工具
cnpm install webpack -g
npm i webpack –save-dev
webpack -v

1、独立版本
我们可以在 Vue.js 的官网上直接下载 vue.min.js 并用 <script> 标签引入
2、使用 CDN 方法
以下推荐国外比较稳定的两个 CDN,国内还没发现哪一家比较好,目前还是建议下载到本地。
Staticfile CDN(国内) : https://cdn.staticfile.org/vue/2.2.2/vue.min.js
unpkg:https://unpkg.com/vue/dist/vue.js, 会保持和 npm 发布的最新的版本一致。
cdnjs : https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js
3、NPM 方法
$ cnpm install vue
命令行工具
Vue.js 提供一个官方命令行工具,可用于快速搭建大型单页应用。
  • 全局安装 vue-cli
    $ cnpm install –global vue-cli
    Vue CLI 的包名称由 vue-cli 改成了 @vue/cli。 如果你已经全局安装了旧版本的 vue-cli (1.x 或 2.x),你需要先通过 npm uninstall vue-cli -g 或 yarn global remove vue-cli 卸载它。
    npm install -g @vue/cli
    yarn global add @vue/cli
    vue -V
    本地全局配置一下chormedriver源,打开终端就一个命令:
    npm config set chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver

vue create 项目名
vue ui

创建一个基于 webpack 模板的新项目

Vue CLI 3 和旧版使用了相同的vue命令,所以 Vue CLI 2 (vue-cli) 被覆盖了。如果你仍然需要使用旧版本的vue init功能,你可以全局安装一个桥接工具:安装完后 就还可以使用 vue init 命令
cnpm install -g @vue/cli-init

vue init webpack my-project
– 这里需要进行一些配置,默认回车即可
This will install Vue 2.x version of the template.
For Vue 1.x use: vue init webpack#1.0 my-project
? Project name my-project
? Project description A Vue.js project
? Author runoob test@runoob.com
? Vue build standalone
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Setup unit tests with Karma + Mocha? Yes
? Setup e2e tests with Nightwatch? Yes
vue-cli · Generated “my-project”.
To get started:
cd my-project
npm install
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
进入项目,安装并运行:
$ cd my-project
$ cnpm install
$ cnpm run dev

npm和yarn命令对比npm yarn

npm install
yarn
npm install react –save
yarn add react
npm uninstall react –save
yarn remove react
npm install react –save-dev
yarn add react –dev
npm update –save
yarn upgrade

1.node+webpack+npm(运行环境)
2.vue+vue-router+vuex(框架技术)
3.element-ui、iview、vant(UI组件库)

主流的vue-cli脚手架,在小程序方面用的是mpvue-cli脚手架
采用主流的编辑器,配置相应的eslint语法规范
eslint配置
{
// vscode默认启用了根据文件类型自动设置tabsize的选项
“editor.detectIndentation”:false,
// 重新设定tabsize技术培训1- 111 -本文档使用看云 构建
“editor.tabSize”:2,
// #每次保存的时候自动格式化
“editor.formatOnSave”:true,
// #每次保存的时候将代码按eslint格式进行修复
“eslint.autoFixOnSave”:true,
// 添加 vue 支持
“eslint.validate”: [”javascript”,”javascriptreact”,{“language”:”vue”,”autoFix”:true}],
// #让函数(名)和后面的括号之间加个空格
“javascript.format.insertSpaceBeforeFunctionParenthesis”:true,
// #这个按用户自身习惯选择
“vetur.format.defaultFormatter.html”:”js-beautify-html”,
// #让vue中的js按编辑器自带的ts格式进行格式化
“vetur.format.defaultFormatter.js”:”vscode-typescript”,”vetur.format.defaultFormatter.scss”:”prettier”,”vetur.format.defaultFormatterOptions”:{“js-beautify-html”:{“wrap_attributes”:”force-aligned”
// #vue组件中html代码格式化样式
}}}


错误解决

  1. npm run 运行项目时报错: getaddrinfo ENOTFOUND x86_64-apple-darwin13.4.0
    unset HOST
    sudo vi /etc/hosts加:127.0.0.1 localhost
    修改/etc/hosts,在里面增加一行:127.0.0.1 x86_64-apple-darwin13.4.0