6月3
1、vuex
2、vue-bus: 一个 Vue.js 事件中心插件https://github.com/yangmingshan/vue-bus
3、$emit()
4、$dispatch()和$broadcast()(vue2.x废弃)
5、父链this.$parent.message = '来自组件component-a的信息'
6、子组件索引
[codes=c#]
this.$ref.commA.message
[/codes]
7、props
8、$attrs
9、others
2、vue-bus: 一个 Vue.js 事件中心插件https://github.com/yangmingshan/vue-bus
3、$emit()
4、$dispatch()和$broadcast()(vue2.x废弃)
5、父链this.$parent.message = '来自组件component-a的信息'
6、子组件索引
[codes=c#]
this.$ref.commA.message
[/codes]
7、props
8、$attrs
9、others
6月3
ui框架
webpack按需打包
webpack axios跨域代理
i18n多语言支持
vuex组件通信(vue bus)
动态router加载
await async异步流控制(step.js)
项目目录最佳实践(config,services(http inteceptor),utils,docs,data(mock),filters,directives,components,views)
测试
代码检查
webpack按需打包
webpack axios跨域代理
i18n多语言支持
vuex组件通信(vue bus)
动态router加载
await async异步流控制(step.js)
项目目录最佳实践(config,services(http inteceptor),utils,docs,data(mock),filters,directives,components,views)
测试
代码检查
6月3
1、全局注册(这种方式注册组件必须在vue实例化之前声明)
[codes=c#]
Vue.component('tag-name',{})
[/codes]
2、局部注册
[codes=c#]
var Child = {
template: '
}
new Vue({
// ...
components: {
// 将只在父模板可用
'my-component': Child
}
})
[/codes]
3、扩展实例
[codes=c#]
// 定义一个混合对象
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// 定义一个使用混合对象的组件
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"
[/codes]
[codes=c#]
Vue.component('tag-name',{})
[/codes]
2、局部注册
[codes=c#]
var Child = {
template: '
A custom component!
'}
new Vue({
// ...
components: {
//
'my-component': Child
}
})
[/codes]
3、扩展实例
[codes=c#]
// 定义一个混合对象
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// 定义一个使用混合对象的组件
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"
[/codes]
6月2
vuejs大型spa的webpack打包文件太大,如何破
1、按需引入组件,例如使用了button则引入button,而不是全局引入ui库(此需要配置打包文件)
例如:vantui
全局的这么玩,但这样全部打包了
[codes=c#]
import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/vant-css/index.css';
Vue.use(Vant);
[/codes]
按需的这么玩
[codes=c#]
//Use babel-plugin-import (Recommended)
npm i babel-plugin-import -D
// set babel config in .babelrc or babel-loader
// Note: Don't set libraryDirectory if you are using webpack 1.
{
"plugins": [
["import", {
"libraryName": "vant",
"libraryDirectory": "es",
"style": true
}]
]
}
Then you can import components from vant, equivalent to import manually below.
import { Button } from 'vant';
[/codes]
1、Webpack打包后体积过大的优化思路
1、按需引入组件,例如使用了button则引入button,而不是全局引入ui库(此需要配置打包文件)
例如:vantui
全局的这么玩,但这样全部打包了
[codes=c#]
import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/vant-css/index.css';
Vue.use(Vant);
[/codes]
按需的这么玩
[codes=c#]
//Use babel-plugin-import (Recommended)
npm i babel-plugin-import -D
// set babel config in .babelrc or babel-loader
// Note: Don't set libraryDirectory if you are using webpack 1.
{
"plugins": [
["import", {
"libraryName": "vant",
"libraryDirectory": "es",
"style": true
}]
]
}
Then you can import components from vant, equivalent to import manually below.
import { Button } from 'vant';
[/codes]
1、Webpack打包后体积过大的优化思路
6月1
1、weinre
weinre
安装nodejs
安装工具包
[codes=c#]npm g-g intall weinre[/codes]
开启工具终端
[codes=c#]weinre -httpPort 8008 -boundHost -all-[/codes]
打开http终端http://你的ip:8008/
在h5中签入
[codes=c#]
[/codes]
打开http终端http://你的ip:8008/可以查看日志,例如console,network等

2、鹅厂出品的vconsole
[codes=c#]
[/codes]

3、基于 WebSocket 的前端远程实时 LOG 工具
例如:https://github.com/bigggge/AirLog
eruda
这个和vconsole类似
https://github.com/liriliri/eruda
weinre
安装nodejs
安装工具包
[codes=c#]npm g-g intall weinre[/codes]
开启工具终端
[codes=c#]weinre -httpPort 8008 -boundHost -all-[/codes]
打开http终端http://你的ip:8008/
在h5中签入
[codes=c#]
[/codes]
打开http终端http://你的ip:8008/可以查看日志,例如console,network等
2、鹅厂出品的vconsole
[codes=c#]
[/codes]
3、基于 WebSocket 的前端远程实时 LOG 工具
例如:https://github.com/bigggge/AirLog
eruda
这个和vconsole类似
https://github.com/liriliri/eruda
6月1
先看下这段流氓代码
[codes=c#]
!function test() {
// 捕获异常,递归次数过多调试工具会抛出异常。
try{
!function cir(i)
{
// 当打开调试工具后,抛出异常,setTimeout执行test无参数,此时i == NaN,("" + i / i).length == 3
// debugger设置断点
( 1 !== ( "" + i / i).length || 0===a ) && function(){}.constructor("debugger")(),cir(++i);
} (0)
} catch(e) {
setTimeout(test,500)
}
}();
[/codes]
问题复现
一次扒某网站的前端代码,打开控制台要看Network,结果发现他们页面一打开控制台就不断的debugger,100ms一次,很影响看页面内容。就像下面这样的

问题分析
每次在断点处停下来的时候页面都会跳到source这个tab页面,也能够看到他的debugger的代码,其实他的实现很简单,只有这一行代码
[codes=c#](function() {var a = new Date(); debugger; return new Date() - a > 100;}())[/codes]
虽然简单,但是却很有效。
不停地打断你,页面跳到source页面,阻止你看他代码不
断的产生不可回收的对象,占据你的内存,造成内存泄漏,没过多久浏览器就会卡顿
所以他带来的影响还是挺大的,我们需要解决这个问题。
问题解决
这个问题解决起来还是蛮简单的,问题解决只需要一句话:禁止断点。
而对应的操作是在Chrome控制台的Source Tab页点击Deactivate breakpoints按钮或者按下Ctrl + f8(下图)。

这样就能禁用断点了,问题就得到了解决,但是当你需要调试的时候记得要起他哦。很简单的操作,但是你如果对Chrome控制台调试不熟悉的话还是比较头疼的。在这里记录一下,分享给更多的人。
[codes=c#]
!function test() {
// 捕获异常,递归次数过多调试工具会抛出异常。
try{
!function cir(i)
{
// 当打开调试工具后,抛出异常,setTimeout执行test无参数,此时i == NaN,("" + i / i).length == 3
// debugger设置断点
( 1 !== ( "" + i / i).length || 0===a ) && function(){}.constructor("debugger")(),cir(++i);
} (0)
} catch(e) {
setTimeout(test,500)
}
}();
[/codes]
问题复现
一次扒某网站的前端代码,打开控制台要看Network,结果发现他们页面一打开控制台就不断的debugger,100ms一次,很影响看页面内容。就像下面这样的
问题分析
每次在断点处停下来的时候页面都会跳到source这个tab页面,也能够看到他的debugger的代码,其实他的实现很简单,只有这一行代码
[codes=c#](function() {var a = new Date(); debugger; return new Date() - a > 100;}())[/codes]
虽然简单,但是却很有效。
不停地打断你,页面跳到source页面,阻止你看他代码不
断的产生不可回收的对象,占据你的内存,造成内存泄漏,没过多久浏览器就会卡顿
所以他带来的影响还是挺大的,我们需要解决这个问题。
问题解决
这个问题解决起来还是蛮简单的,问题解决只需要一句话:禁止断点。
而对应的操作是在Chrome控制台的Source Tab页点击Deactivate breakpoints按钮或者按下Ctrl + f8(下图)。
这样就能禁用断点了,问题就得到了解决,但是当你需要调试的时候记得要起他哦。很简单的操作,但是你如果对Chrome控制台调试不熟悉的话还是比较头疼的。在这里记录一下,分享给更多的人。
6月1
1、vue proxyTable接口跨域请求调试
或参考开发阶段 API 请求代理
在vue-cli项目中的config文件夹下的index.js配置文件中,dev长这样子:
[codes=c#]
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false
}
[/codes]
服务器提供的接口如果长这样https://www.exaple.com/server_new/login,我们把域名提取出来如https://www.exaple.com;
在config中新建一个文件命名为proxyConfig.js :
[codes=c#]
module.exports = {
proxy: {
'/apis': { //将www.exaple.com印射为/apis
target: 'https://www.exaple.com', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite的,
}
}
}
}
[/codes]
config文件夹下的index.js引入proxyConfig.js:
[codes=c#]
var proxyConfig = require('./proxyConfig')
config文件夹下的index.js中的dev改成:
[codes=c#]
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: proxyConfig.proxy,
cssSourceMap: false
}
[/codes]
重启项目npm run dev:
你会发现出现了这个
这个时候我们已经设置好了本地API代理了
修改本地hosts文件
文件路径一般是C:\Window\System32\drivers\etc,打开hosts文件,在这一段下面把localhost设置进去
[codes=c#]
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 activate.adobe.com
127.0.0.1 practivate.adobe.com
127.0.0.1 lmlicenses.wip4.adobe.com
127.0.0.1 lm.licenses.adobe.com
127.0.0.1 na1r.services.adobe.com
127.0.0.1 hlrcv.stage.adobe.com
[/codes]
localhost www.exaple.com
搞定
此时我们已经完全解决了跨域问题,以及本地测试后台无法向我们本地环境设置cookie的情况了。
2、后端设置请求头部Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com
后端设置请求头部Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com
前端post请求设置withCredentials=true
这里用了axios的请求数据方法代码如下:
[codes=c#]
import axios from 'axios'
import config from '../config'
export default {
request (method, uri, data, headerConfig = {withCredentials: true}) {
if (!method) {
console.error('API function call requires method argument')
return
}
if (!uri) {
console.error('API function call requires uri argument')
return
}
let url = config.serverURI + uri
return axios({ method, url, data, ...headerConfig })
}
}
[/codes]
jQuery的$.ajax::
[codes=c#]
$.ajax({
type: "POST",
url: "http://www.xxx.com/api.php",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
}).then((json) => {
// balabala...
})
[/codes]
3、jsonp
jsonp也是一种解决跨域的方法,不过我从来没有用过,在网上查了下资料,jsonp的原理是script标签引入js是不受域名限制的, 由于是模拟插入script标签, 所以不可以用post请求。
4、nginx配置
最近使用vue开发一个功能,npm run build之后打包的代码放在了a.com.cn下但是php接口部署在了b.com下,那么问题来了,如何让后端接口支持跨域。有两种方法:
让后端在返回数据的时候设置下返回请求的header,这种方法比较不稳定,因为接口一旦多了就得改好多代码,而且每次出了问题还得去找后端开发改代码,很烦。
另一种方法是,自己配置nginx,首先ssh登录到部署接口所在的服务器,修改nginx配置,在http对象中加入两行代码:
[codes=c#]
http {
// 需要加入的代码
add_header Access-Control-Allow-Origin http://a.com.cn
add_header Access-Control-Allow-Credentials true
server {
// b.com.cn的具体配置
}
}
[/codes]
改完重启下nginx,然后在vue项目中,在导入axios的地方加如以下代码:
[codes=c#]
import axios from 'axios'
axios.defaults.withCredentials = true
[/codes]
然后测试,发现就可以跨域了。
或参考开发阶段 API 请求代理
在vue-cli项目中的config文件夹下的index.js配置文件中,dev长这样子:
[codes=c#]
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false
}
[/codes]
服务器提供的接口如果长这样https://www.exaple.com/server_new/login,我们把域名提取出来如https://www.exaple.com;
在config中新建一个文件命名为proxyConfig.js :
[codes=c#]
module.exports = {
proxy: {
'/apis': { //将www.exaple.com印射为/apis
target: 'https://www.exaple.com', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite的,
}
}
}
}
[/codes]
config文件夹下的index.js引入proxyConfig.js:
[codes=c#]
var proxyConfig = require('./proxyConfig')
config文件夹下的index.js中的dev改成:
[codes=c#]
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: proxyConfig.proxy,
cssSourceMap: false
}
[/codes]
重启项目npm run dev:
你会发现出现了这个
这个时候我们已经设置好了本地API代理了
修改本地hosts文件
文件路径一般是C:\Window\System32\drivers\etc,打开hosts文件,在这一段下面把localhost设置进去
[codes=c#]
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 activate.adobe.com
127.0.0.1 practivate.adobe.com
127.0.0.1 lmlicenses.wip4.adobe.com
127.0.0.1 lm.licenses.adobe.com
127.0.0.1 na1r.services.adobe.com
127.0.0.1 hlrcv.stage.adobe.com
[/codes]
localhost www.exaple.com
搞定
此时我们已经完全解决了跨域问题,以及本地测试后台无法向我们本地环境设置cookie的情况了。
2、后端设置请求头部Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com
后端设置请求头部Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com
前端post请求设置withCredentials=true
这里用了axios的请求数据方法代码如下:
[codes=c#]
import axios from 'axios'
import config from '../config'
export default {
request (method, uri, data, headerConfig = {withCredentials: true}) {
if (!method) {
console.error('API function call requires method argument')
return
}
if (!uri) {
console.error('API function call requires uri argument')
return
}
let url = config.serverURI + uri
return axios({ method, url, data, ...headerConfig })
}
}
[/codes]
jQuery的$.ajax::
[codes=c#]
$.ajax({
type: "POST",
url: "http://www.xxx.com/api.php",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
}).then((json) => {
// balabala...
})
[/codes]
3、jsonp
jsonp也是一种解决跨域的方法,不过我从来没有用过,在网上查了下资料,jsonp的原理是script标签引入js是不受域名限制的, 由于是模拟插入script标签, 所以不可以用post请求。
4、nginx配置
最近使用vue开发一个功能,npm run build之后打包的代码放在了a.com.cn下但是php接口部署在了b.com下,那么问题来了,如何让后端接口支持跨域。有两种方法:
让后端在返回数据的时候设置下返回请求的header,这种方法比较不稳定,因为接口一旦多了就得改好多代码,而且每次出了问题还得去找后端开发改代码,很烦。
另一种方法是,自己配置nginx,首先ssh登录到部署接口所在的服务器,修改nginx配置,在http对象中加入两行代码:
[codes=c#]
http {
// 需要加入的代码
add_header Access-Control-Allow-Origin http://a.com.cn
add_header Access-Control-Allow-Credentials true
server {
// b.com.cn的具体配置
}
}
[/codes]
改完重启下nginx,然后在vue项目中,在导入axios的地方加如以下代码:
[codes=c#]
import axios from 'axios'
axios.defaults.withCredentials = true
[/codes]
然后测试,发现就可以跨域了。
6月1
以下引用:vuejs采坑记录https://blog.csdn.net/xidongdong1/article/details/78613654
前言:记录在学Vue中需要注意的问题
1.给link添加事件、给组件绑定原生事件
在vue-router1中使用v-link写入路由,但是在vue-router2中要使用router-link写入路由,在浏览器渲染的时候会把router-link渲染成a。
有时候需要为router-link注册事件,对于一般的html元素,直接使用@click="eventFun"即可,但是对于router-link,像普通html元素那样注册事件后并不管用,需要添加.native才会成功注册。
事实上给组件绑定原生事件就需要.native修饰v-on,否则无法注册成功。
[codes=c#]
错误事例:
" @mouseover="test()">
@click="toggleName=''">
[/codes]
2.修改prop中的数据
每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。如果你这么做了,Vue 会在控制台给出警告。
在两种情况下,我们很容易忍不住想去修改 prop 中数据:
Prop 作为初始值传入后,子组件想把它当作局部数据来用;
Prop 作为原始数据传入,由子组件处理成其它数据输出。
对这两种情况,正确的应对方式是:
定义一个局部变量,并用 prop 的值初始化它:
[codes=c#]
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
定义一个计算属性,处理 prop 的值并返回:
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
[/codes]
3.我需要遍历的数组值更新了,值也赋值了,为什么视图不更新?
因为有局限性啊,官方文档也说的很清楚,一般我们常用的手段是使用:this.$set(obj,item,value)
官方文档如下:
由于 JavaScript 的限制,Vue 不能检测以下变动的数组:
当你利用索引直接设置一个项时,例如:vm.items[indexOfItem] = newValue
当你修改数组的长度时,例如:vm.items.length = newLength
为了解决第一类问题,以下两种方式都可以实现和 vm.items[indexOfItem] = newValue 相同的效果,同时也将触发状态更新:
[codes=c#]
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
// Array.prototype.splice
example1.items.splice(indexOfItem, 1, newValue)
为了解决第二类问题,你可以使用 splice:
example1.items.splice(newLength)
[/codes]
还是由于
JavaScript 的限制,Vue 不能检测对象属性的添加或删除,对于已经创建的实例,Vue
不能动态添加根级别的响应式属性。
但是,可以使用 Vue.set(object,
key, value) 方法向嵌套对象添加响应式属性。例如,对于:
[codes=c#]
var vm = new Vue({
data: {
userProfile: {
name: 'Anika'
}
}
})
[codes]
你可以添加一个新的 age 属性到嵌套的 userProfile 对象:
[codes=c#]
Vue.set(vm.userProfile, 'age', 27)
[/codes]
有时你可能需要为已有对象赋予多个新属性,比如使用 Object.assign() 或 _.extend()。
在这种情况下,你应该用两个对象的属性创建一个新的对象。所以,如果你想添加新的响应式属性,不要像这样:
[codes=c#]
Object.assign(this.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})
你应该这样做:
this.userProfile = Object.assign({}, this.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})
[/codes]
4.建议尽可能在使用 v-for 时提供 key
[codes=c#]
[/codes]
它是 Vue 识别节点的一个通用机制,key 并不与 v-for 特别关联,key 还具有其他用途,我们将在后面的指南中看到其他用途,后续补充
(2.2.0+ 的版本里,当在组件中使用 v-for 时,key 现在是必须的。)
5.路由模式改为history后,除了首次启动首页没报错,刷新访问路由都报错
必须给对应的服务端配置查询的主页面..也可以认为是主路由入口的引导。。。Vue-Router官方文档链接
(https://router.vuejs.org/zh-cn/essentials/history-mode.html)包括动态路由匹配、向路由组件传递props等基础知识
6.Uncaught ReferenceError: xxx is not define
实例内的 data 对应的变量没有声明
你导入模块报这个错误,那绝逼是导出没写好
7.Error in render function:"Type Error: Cannot read property 'xxx' of undefined"
这种问题大多都是初始化的姿势不对;
比如引入echart这些...仔细去了解下生命周期,再来具体初始化;
vue 组件有时候也会(嵌套组件或者 props传递初始化)..也是基本这个问题
8.Failed to mount component: template or render function not defined
组件挂载失败,问题只有这么几个
组件没有正确引入; 挂载点顺序错了了;
自行动手排查
9.[Vue warn]: Error in render function: "TypeError: Cannot read property '0' of undefined"
想将seller传递给子组件使用,但是我们ajax获取数据是异步过程,也就是说一开始在初始化seller时是空对象,所以把此时的seller传给header就是undefined
使用v-if可以解决报错问题,和created为空问题
【详解vue2父组件传递props异步数据到子组件的问题】【http://www.jb51.net/article/117447.htm】
10.vue-cli 新建项目 缺少dev-server.js和dev-client.js , 怎么模拟数据
在使用vue开发过程中,难免需要去本地数据地址进行请求,而原版配置在dev-server.js中,新版vue-webpack-template已经删除dev-server.js,改用webpack.dev.conf.js代替,所以 配置本地访问在webpack.dev.conf.js里配置即可。
[codes=c#]
//首先
const express = require('express')
const app = express()
var appData = require('../data.json')
var seller = appData.seller
var goods = appData.goods
var ratings = appData.ratings
var apiRoutes = express.Router()
app.use('/api', apiRoutes)
//找到devServer,添加
before(app) {
app.get('/api/seller', (req, res) => {
res.json({
// 这里是你的json内容
errno: 0,
data: seller
})
}),
app.get('/api/goods', (req, res) => {
res.json({
// 这里是你的json内容
errno: 0,
data: goods
})
}),
app.get('/api/ratings', (req, res) => {
res.json({
// 这里是你的json内容
errno: 0,
data: ratings
})
})
}
[/codes]
11.[WDS] Errors while compiling. Reload prevented.
有一种错误的原因是import的路径不对
[codes=c#]
import header from '@views/header/header.vue'
[/codes]
12.应当避免在模板或计算属性中使用 $refs
$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅是一个直接操作子组件的应急方案——应当避免在模板或计算属性中使用 $refs
13、vuejs nginx子目录访问
https://www.jianshu.com/p/05f889faa74b
14、vuejs elmentui踩坑日记
vue使用过程中遇到的坑--个人总结(不定时更新)
修改了computed的值无效
请使用get,set
[codes=c#]
computed: {
classState: {
get: function(){
return this.classJudge
},
set: function(index){
if (index%2==0) {
this.classJudge = even
} else {
this.classJudge = odd
}
}
}
}
[/codes]
前言:记录在学Vue中需要注意的问题
1.给link添加事件、给组件绑定原生事件
在vue-router1中使用v-link写入路由,但是在vue-router2中要使用router-link写入路由,在浏览器渲染的时候会把router-link渲染成a。
有时候需要为router-link注册事件,对于一般的html元素,直接使用@click="eventFun"即可,但是对于router-link,像普通html元素那样注册事件后并不管用,需要添加.native才会成功注册。
事实上给组件绑定原生事件就需要.native修饰v-on,否则无法注册成功。
[codes=c#]
错误事例:
[/codes]
2.修改prop中的数据
每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。如果你这么做了,Vue 会在控制台给出警告。
在两种情况下,我们很容易忍不住想去修改 prop 中数据:
Prop 作为初始值传入后,子组件想把它当作局部数据来用;
Prop 作为原始数据传入,由子组件处理成其它数据输出。
对这两种情况,正确的应对方式是:
定义一个局部变量,并用 prop 的值初始化它:
[codes=c#]
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
定义一个计算属性,处理 prop 的值并返回:
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
[/codes]
3.我需要遍历的数组值更新了,值也赋值了,为什么视图不更新?
因为有局限性啊,官方文档也说的很清楚,一般我们常用的手段是使用:this.$set(obj,item,value)
官方文档如下:
由于 JavaScript 的限制,Vue 不能检测以下变动的数组:
当你利用索引直接设置一个项时,例如:vm.items[indexOfItem] = newValue
当你修改数组的长度时,例如:vm.items.length = newLength
为了解决第一类问题,以下两种方式都可以实现和 vm.items[indexOfItem] = newValue 相同的效果,同时也将触发状态更新:
[codes=c#]
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
// Array.prototype.splice
example1.items.splice(indexOfItem, 1, newValue)
为了解决第二类问题,你可以使用 splice:
example1.items.splice(newLength)
[/codes]
还是由于
JavaScript 的限制,Vue 不能检测对象属性的添加或删除,对于已经创建的实例,Vue
不能动态添加根级别的响应式属性。
但是,可以使用 Vue.set(object,
key, value) 方法向嵌套对象添加响应式属性。例如,对于:
[codes=c#]
var vm = new Vue({
data: {
userProfile: {
name: 'Anika'
}
}
})
[codes]
你可以添加一个新的 age 属性到嵌套的 userProfile 对象:
[codes=c#]
Vue.set(vm.userProfile, 'age', 27)
[/codes]
有时你可能需要为已有对象赋予多个新属性,比如使用 Object.assign() 或 _.extend()。
在这种情况下,你应该用两个对象的属性创建一个新的对象。所以,如果你想添加新的响应式属性,不要像这样:
[codes=c#]
Object.assign(this.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})
你应该这样做:
this.userProfile = Object.assign({}, this.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})
[/codes]
4.建议尽可能在使用 v-for 时提供 key
[codes=c#]
[/codes]
它是 Vue 识别节点的一个通用机制,key 并不与 v-for 特别关联,key 还具有其他用途,我们将在后面的指南中看到其他用途,后续补充
(2.2.0+ 的版本里,当在组件中使用 v-for 时,key 现在是必须的。)
5.路由模式改为history后,除了首次启动首页没报错,刷新访问路由都报错
必须给对应的服务端配置查询的主页面..也可以认为是主路由入口的引导。。。Vue-Router官方文档链接
(https://router.vuejs.org/zh-cn/essentials/history-mode.html)包括动态路由匹配、向路由组件传递props等基础知识
6.Uncaught ReferenceError: xxx is not define
实例内的 data 对应的变量没有声明
你导入模块报这个错误,那绝逼是导出没写好
7.Error in render function:"Type Error: Cannot read property 'xxx' of undefined"
这种问题大多都是初始化的姿势不对;
比如引入echart这些...仔细去了解下生命周期,再来具体初始化;
vue 组件有时候也会(嵌套组件或者 props传递初始化)..也是基本这个问题
8.Failed to mount component: template or render function not defined
组件挂载失败,问题只有这么几个
组件没有正确引入; 挂载点顺序错了了;
自行动手排查
9.[Vue warn]: Error in render function: "TypeError: Cannot read property '0' of undefined"
想将seller传递给子组件使用,但是我们ajax获取数据是异步过程,也就是说一开始在初始化seller时是空对象,所以把此时的seller传给header就是undefined
使用v-if可以解决报错问题,和created为空问题
【详解vue2父组件传递props异步数据到子组件的问题】【http://www.jb51.net/article/117447.htm】
10.vue-cli 新建项目 缺少dev-server.js和dev-client.js , 怎么模拟数据
在使用vue开发过程中,难免需要去本地数据地址进行请求,而原版配置在dev-server.js中,新版vue-webpack-template已经删除dev-server.js,改用webpack.dev.conf.js代替,所以 配置本地访问在webpack.dev.conf.js里配置即可。
[codes=c#]
//首先
const express = require('express')
const app = express()
var appData = require('../data.json')
var seller = appData.seller
var goods = appData.goods
var ratings = appData.ratings
var apiRoutes = express.Router()
app.use('/api', apiRoutes)
//找到devServer,添加
before(app) {
app.get('/api/seller', (req, res) => {
res.json({
// 这里是你的json内容
errno: 0,
data: seller
})
}),
app.get('/api/goods', (req, res) => {
res.json({
// 这里是你的json内容
errno: 0,
data: goods
})
}),
app.get('/api/ratings', (req, res) => {
res.json({
// 这里是你的json内容
errno: 0,
data: ratings
})
})
}
[/codes]
11.[WDS] Errors while compiling. Reload prevented.
有一种错误的原因是import的路径不对
[codes=c#]
import header from '@views/header/header.vue'
[/codes]
12.应当避免在模板或计算属性中使用 $refs
$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅是一个直接操作子组件的应急方案——应当避免在模板或计算属性中使用 $refs
13、vuejs nginx子目录访问
https://www.jianshu.com/p/05f889faa74b
14、vuejs elmentui踩坑日记
vue使用过程中遇到的坑--个人总结(不定时更新)
修改了computed的值无效
请使用get,set
[codes=c#]
computed: {
classState: {
get: function(){
return this.classJudge
},
set: function(index){
if (index%2==0) {
this.classJudge = even
} else {
this.classJudge = odd
}
}
}
}
[/codes]
5月31
前端
1、promise.then
2、Step.js 使用教程(附源码解析)
3、Async.js中文详解
其他
1、Generator co http://www.ruanyifeng.com/blog/2015/05/async.html
2、async await 可以参考阅读https://www.jianshu.com/p/7bd8d5e87965
2.1、vue : async / await 的应用
api.js
[codes=c#]
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
var async2 = async function () {
let data = await new Promise((resolve)=>{
setTimeout(()=>{
resolve({"errocode":0,"errmsg":"ok"})
console.log("async2");
},3000)
})
return data
}
export const async1 = async function () {
await async2();
let data = await new Promise((resolve)=>{
setTimeout(()=>{
resolve({"errocode":0,"errmsg":"ok"})
console.log("async1");
})
})
return data
}
[/codes]
app.vue
[codes=c#]
import { async1,async2 } from '../../api/api';
...
created(){
async1().then((v)=>{
console.info(v);
});
},
...
[/codes]
vue使用async/await 报错“Syntax Error: await is a reserved word“””
[codes=c#]
引入babel-plugin-transform-runtime包,然后在.babelrc加上
{
"presets": [
["env", { "modules": false }],
"stage-2"
],
"plugins": ["transform-runtime"],
"comments": false,
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": [ "istanbul" ]
}
}
}
[/codes]


async/await 更好的异步解决方案https://segmentfault.com/a/1190000012411744
1、promise.then
2、Step.js 使用教程(附源码解析)
引用
Step.js(https://github.com/creationix/step)是控制流程工具(大小仅 150 行代码),解决回调嵌套层次过多等问题。适用于读文件、查询数据库等回调函数相互依赖,或者分别获取内容最后组合数据返回等应用情景。异步执行简单地可以分为“串行执行”和“并行”执行,下面我们分别去看看。
3、Async.js中文详解
引用
Async的内容分为三部分: 流程控制:简化十种常见流程的处理 集合处理:如何使用异步操作处理集合中的数据 工具类:几个常用的工具类
其他
1、Generator co http://www.ruanyifeng.com/blog/2015/05/async.html
2、async await 可以参考阅读https://www.jianshu.com/p/7bd8d5e87965
2.1、vue : async / await 的应用
api.js
[codes=c#]
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
var async2 = async function () {
let data = await new Promise((resolve)=>{
setTimeout(()=>{
resolve({"errocode":0,"errmsg":"ok"})
console.log("async2");
},3000)
})
return data
}
export const async1 = async function () {
await async2();
let data = await new Promise((resolve)=>{
setTimeout(()=>{
resolve({"errocode":0,"errmsg":"ok"})
console.log("async1");
})
})
return data
}
[/codes]
app.vue
[codes=c#]
import { async1,async2 } from '../../api/api';
...
created(){
async1().then((v)=>{
console.info(v);
});
},
...
[/codes]
vue使用async/await 报错“Syntax Error: await is a reserved word“””
[codes=c#]
引入babel-plugin-transform-runtime包,然后在.babelrc加上
{
"presets": [
["env", { "modules": false }],
"stage-2"
],
"plugins": ["transform-runtime"],
"comments": false,
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": [ "istanbul" ]
}
}
}
[/codes]
async/await 更好的异步解决方案https://segmentfault.com/a/1190000012411744