socks-node 报错
用 vue cli 生成的项目在浏览器打开,在控制台报错:sockjs-node ERR_CONNECTION_REFUSED,从而热更新功能无法使用,每次更改只能手动刷新浏览器。

GitHub 上也有相关的 issues:
原因是开发的时候网络环境变更导致,比如切换无线网络,导致开发服务器的IP地址换了,这样开发服务器会不知道如何确定访问源。
最后找到解决办法:固定 host 和 port,或者直接重启。

404 被代理到跟目录
vue cli3 生成的项目将 url 改成任意路径,都会匹配到跟组件,资源请求路径不对也不会出现 404,状态码也会是 200。因为 devServer.historyApiFallback 默认为 true,任意的 404 响应都被替代为 index.html,即使使用的是 hash 路由。需要在 vue.config.js 中修改。
module.exports = {devServer: {historyApiFallback: false}}
vue-devtools 报错
使用 vue-devtools 工具报错 hook.flushStoreModules is no a function,组件也不显示,vuex 不显示,点击 Refresh 按钮后恢复正常。

解决方法是:禁用 vue-performance 插件。
axios post
1,post 方法传的参数需要放在 data 里,如果放在params里,都会被拼在请求的url后:
this.$axios({url: '/rockets/user/action.do',method: 'POST',params: {method: 'login',userName: this.userName,passWord: this.passWord,verCode: this.verCode},// headers: {// 'Content-Type': 'application/x-www-form-urlencoded'// }})
config 参数为:

params 的内容都会被拼在 url 后面,成为 /rockets/user/action.do?method=login&userName= 的形式,后端可以拿到数据,但和 get 请求一样,参数是明文的。
2,params 和 data 有区别,直接传 url 和数据对象,表示 data 的值为数据,而且被转成了字符串的形式:
this.$axios.post('/rockets/user/action.do', {method: 'login',userName: this.userName,passWord: this.passWord,verCode: this.verCode})
config 参数为:

数据格式是Request Payload,后端接收不到参数。解决方法:axios post请求传参问题,最简单的方法就是使用 qs 将数据拼成 url 参数的形式。
将数据拼接成 url 参数的形式也可以这么实现:
var params = new URLSearchParams();params.append('user', 'value1');params.append('name', 'value2');axios.post('/demo', params);
监听 vuex state 变化
<template><div>{{userInfo}}</div></template><script>export default {computed: {userInfo() {console.log('computed')return this.$store.state.userInfo}},watch: {userInfo(info) {console.log('watch userInfo')},'$store.state.userInfo': {hanhdle: function(inof) {console.log('watch $store')}}},created() {setTimeout(() => {this.$store.commit('updateInfo', {name: 'leo'})}, 2000)}}</script>
// store.jsVues.Store({state: {userInfo: {// name: 'test'}},mutations: {updateInfo(state, info) {// 1state.userInfo = info// 2Vue.set(state.userInfo, 'name', info.name);// 3state.userInfo = {...state.userInfo,...info}// 4state.userInfo = Object.assign(state.userInfo, info);// 5state.userInfo = Object.assign({}, state.userInfo, info);}}})
2秒后提交 mutation,修改 state 中的值,模版中 userInfo 的值会更新,正常情况下会打印 ‘computed’ ‘watch userInfo’ ‘watch $store’。
事实上 state.userInfo 是否有初始 key,更新 state 的方式不同,打印不同。
用方法 1,3,5修改 state 效果相同,都是给原来的对象赋一个值新的值,不管 userInfo 有没有初始的 name,都会打印 ‘computed’ ‘watch userInfo’ ‘wath $store’;
用方法2,没有初始 ‘name’ 时,会依次打印一次,第二次提交 mutation 不会打印;有初始的 name 值,不会打印。
方法4更新了 state.userInfo 对象,返回值还是对象本身,没有被重新赋值,不满足 vue 的响应规则。

对象属性监听
通常添加对象属性都是通过 $set 方法,或者直接给对象赋值,才能检测到变化,这仅仅是属性的添加和删除。如果初始化时已经有的属性, Vue 会在初始化实例时对属性执行 getter/setter 转化过程,所以属性在 data 对象上存在会让 Vue 转换它,这样是响应的,可以直接赋新值。
插槽样式污染
插槽的部分内容在父组件,样式也在父组件,即使子组件和父组件都使用了 scoped,也可能会出现样式污染的问题,因为插槽部分的 html 节点会有父组件和子组件的两个 scopeId。
父组件:
<div class="data"><card-com><template v-slot:title>传播数据结构分析</template><template v-slot:content><ul class="content"><li><span class="index">1</span><p class="text">传播的主要渠道为“<span>网站</span>”,一共有<span>2759</span>篇报道;</p></li></ul></template></card-com></div>
子组件 <card-com>:
<div class="card-com"><p class="title"><slot name="title"></slot></p><div class="content"><slot name="content"></slot></div></div>
渲染结构:

data-v-d1799a24 为父组件节点,data-v-060ff10e 为子组件节点,两个 id 都有的是插槽内的节点,子组件中对 .content 的样是会污染插槽中的 .content 节点。.content[data="data-v-060ff10e"] 匹配到了两个 .content 节点。
vuex 模块命名空间
store.js
import Vue from 'vue'import Vuex from 'vuex'import hotPointRelate from './hotPointRelate'Vue.use(Vuex)export default new Vuex.Store({state: {},mutations: {},actions: {},modules: {hotPointRelate}})
hotPointRelate.js
export default {namespaced: true,state: {dialogVisible: false},mutations: {// 弹框显示隐藏toggleDialog(state, v) {state.dialogVisible = v;}},actions: {}}
提交 mutation :
this.$store.commit('hotPointRelate/toggleDialog', true);
使用 map 函数简化 带命名空间的绑定函数
computed: {...mapState('some/nested/module', {a: state => state.a,b: state => state.b})},methods: {...mapActions('some/nested/module', ['foo', // -> this.foo()'bar' // -> this.bar()])}
自动导入 vuex 模块
自动导入 ./module 文件夹下的所有 js 文件。require.context
import Vue from 'vue'import Vuex from 'vuex'const path = require('path')Vue.use(Vuex)const files = require.context("./modules", false, /\.js$/);const modules = {};files.keys().forEach(key => {const name = path.basename(key, '.js');modules[name] = files(key).default || files(key);// modules[key.replace(/(\.\/|\.js)/g, "")] = files(key).default;});export default new Vuex.Store({state: {},mutations: {},actions: {},modules})
自动导入 router
// 导入路由const files = require.context("./routers", false, /\.js$/);const routes = [];files.keys().forEach(key => {routes.push(files(key).default);});export default new Router({routes,})
引入图片 作为变量
将打包前的图片路径作为变量,使用会有问题。
<template><img :src="imgUrl" /></template><script>export default {data() {return {imgUrl: '../images/1.png'}}}</script>
可以用变量存打包后的图片路径。
import imgUrl from '../images/1.png'let imgUrl = require('../images/1.png')
echarts 引入中国地区数据
<script src="https://www.echartsjs.com/gallery/vendors/echarts/map/js/china.js"></script>
import chinaJson from './china.json'
vue 引入 public 资源
放在 public 下的图片,通过相对路径引用,一样会被 webpack 打包。
let imgUrl = require('../../public/1.png');console.log(imgUrl);// data:image/png;base64,iVBOR...
任何放置在
public文件夹的静态资源都会被简单的复制,而不经过 webpack。你需要通过绝对路径来引用它们。 — vue cli
在 public/index.html 或其它通过 html-webpack-plugin 用作模板的 HTML 文件中,你需要通过 <%= BASE_URL %> 设置链接前缀。
在模板中,你首先需要向你的组件传入基础 URL:
data () {return {publicPath: process.env.BASE_URL}}
然后:
<img :src="`${publicPath}1.png`">
直接使用 process.env.BASE_URL 报错:
<img :src="process.env.BASE_URL + '1.png'">
组件内部动态引入 public 文件夹下的 js,也可以使用此方法。
let script = document.createElement('script')script.src = this.publicPath + 'a.js'// 引入 public/a.js
图片上传
使用 FormData 对象上传图片。
<template><input type="text" v-model="text"/><input type="file" @change="saveFile" accept="image/*"/><button @click="submit">submit</button></template><script>export default {data() {return {text: ''}},methods: {saveFile(e) {[].forEach.call(e.target.files, file => this.formFile.append('file', file))},submit() {this.formData.append('text', this.text);// submit();}},created() {this.formData = new FormData();}}</script>
this.$axios.post('/upload', this.formFile, {method: 'post',headers: {'Content-Type': 'multipart/form-data'}})
使用 axios 上传图片,遇到问题始终没法上传,发送请求,参数格式不对,formdata 对象的数据被转成了字符串,最终在拦截器里看到如下代码:
axios.interceptors.request.use(config => {if (config.method === 'post') {config.data = qs.stringify(config.data) // post请求格式化数据config.headers['formdata'] = "1";}// ...});
使用 post 请求都被转成字符串了。将判断修改后:
if (config.method === 'post' && Object.prototype.toString.call(config.data) !== '[object FormData]') {// ...}
ref 和 v-for 一起使用
当 ref 和 v-for 一起使用的时候,得到的引用将会是一个包含了对应数据源的这些子组件的数组,即使 ref 的值是唯一的,即使 v-for 遍历的数组长度为1。
<template><div v-for="item in list" :key="item.id"><custom-com ref="'customCom' + item.id"></custom-com></div></template><script>export default {data() {return {list: [{id: 'First'}]}},mounted() {console.log(this.$refs.customComFirst);// 一个长度为1的数组}}</script>
监听子组件的生命周期
<template><child-component @hook:mounted="fn"></child-component></template>
定时器离开页面后未关闭
mounted() {setTimeout(this.init, 2000)}
如果在两秒内离开了当前路由,this.init 还是会被调用。
文件下载
this.$axios.get('url', {params: {},responseType: 'blob'}).then(data => {const url = window.URL.createObjectURL(new Blob([data]));const a = document.createElement('a');a.style.display = 'none';a.href = url;a.setAttribute('download', 'filename');document.body.appendChild(a);a.click();window.URL.revokeObjectURL(a.href);document.body.removeChild(a);})
使用 EventBus 可能存在的问题
事件监听不会在组件销毁后自动移除。
