Vue 项目里戳中你痛点的问题及解决办法(更新)

socks-node 报错

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

image.png

GitHub 上也有相关的 issues:

  1. sockjs-node ERR_CONNECTION_REFUSED when accessing from network
  2. sockjs-node (Not Found)

原因是开发的时候网络环境变更导致,比如切换无线网络,导致开发服务器的IP地址换了,这样开发服务器会不知道如何确定访问源。

最后找到解决办法:固定 host 和 port,或者直接重启。

image.png

404 被代理到跟目录

vue cli3 生成的项目将 url 改成任意路径,都会匹配到跟组件,资源请求路径不对也不会出现 404,状态码也会是 200。因为 devServer.historyApiFallback 默认为 true,任意的 404 响应都被替代为 index.html,即使使用的是 hash 路由。需要在 vue.config.js 中修改。

  1. module.exports = {
  2. devServer: {
  3. historyApiFallback: false
  4. }
  5. }

vue-devtools 报错

使用 vue-devtools 工具报错 hook.flushStoreModules is no a function,组件也不显示,vuex 不显示,点击 Refresh 按钮后恢复正常。

image.png

解决方法是:禁用 vue-performance 插件。

axios post

1,post 方法传的参数需要放在 data 里,如果放在params里,都会被拼在请求的url后:

  1. this.$axios({
  2. url: '/rockets/user/action.do',
  3. method: 'POST',
  4. params: {
  5. method: 'login',
  6. userName: this.userName,
  7. passWord: this.passWord,
  8. verCode: this.verCode
  9. },
  10. // headers: {
  11. // 'Content-Type': 'application/x-www-form-urlencoded'
  12. // }
  13. })

config 参数为:

image.png

params 的内容都会被拼在 url 后面,成为 /rockets/user/action.do?method=login&userName= 的形式,后端可以拿到数据,但和 get 请求一样,参数是明文的。

2,params 和 data 有区别,直接传 url 和数据对象,表示 data 的值为数据,而且被转成了字符串的形式:

  1. this.$axios.post('/rockets/user/action.do', {
  2. method: 'login',
  3. userName: this.userName,
  4. passWord: this.passWord,
  5. verCode: this.verCode
  6. })

config 参数为:

image.png

数据格式是Request Payload,后端接收不到参数。解决方法:axios post请求传参问题,最简单的方法就是使用 qs 将数据拼成 url 参数的形式。

将数据拼接成 url 参数的形式也可以这么实现:

  1. var params = new URLSearchParams();
  2. params.append('user', 'value1');
  3. params.append('name', 'value2');
  4. axios.post('/demo', params);

监听 vuex state 变化

  1. <template>
  2. <div>{{userInfo}}</div>
  3. </template>
  4. <script>
  5. export default {
  6. computed: {
  7. userInfo() {
  8. console.log('computed')
  9. return this.$store.state.userInfo
  10. }
  11. },
  12. watch: {
  13. userInfo(info) {
  14. console.log('watch userInfo')
  15. },
  16. '$store.state.userInfo': {
  17. hanhdle: function(inof) {
  18. console.log('watch $store')
  19. }
  20. }
  21. },
  22. created() {
  23. setTimeout(() => {
  24. this.$store.commit('updateInfo', {
  25. name: 'leo'
  26. })
  27. }, 2000)
  28. }
  29. }
  30. </script>
  1. // store.js
  2. Vues.Store({
  3. state: {
  4. userInfo: {
  5. // name: 'test'
  6. }
  7. },
  8. mutations: {
  9. updateInfo(state, info) {
  10. // 1
  11. state.userInfo = info
  12. // 2
  13. Vue.set(state.userInfo, 'name', info.name);
  14. // 3
  15. state.userInfo = {
  16. ...state.userInfo,
  17. ...info
  18. }
  19. // 4
  20. state.userInfo = Object.assign(state.userInfo, info);
  21. // 5
  22. state.userInfo = Object.assign({}, state.userInfo, info);
  23. }
  24. }
  25. })

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 的响应规则。

image.png

对象属性监听

通常添加对象属性都是通过 $set 方法,或者直接给对象赋值,才能检测到变化,这仅仅是属性的添加和删除。如果初始化时已经有的属性, Vue 会在初始化实例时对属性执行 getter/setter 转化过程,所以属性在 data 对象上存在会让 Vue 转换它,这样是响应的,可以直接赋新值。

插槽样式污染

插槽的部分内容在父组件,样式也在父组件,即使子组件和父组件都使用了 scoped,也可能会出现样式污染的问题,因为插槽部分的 html 节点会有父组件和子组件的两个 scopeId。

父组件:

  1. <div class="data">
  2. <card-com>
  3. <template v-slot:title>传播数据结构分析</template>
  4. <template v-slot:content>
  5. <ul class="content">
  6. <li>
  7. <span class="index">1</span>
  8. <p class="text">传播的主要渠道为“<span>网站</span>”,一共有<span>2759</span>篇报道;</p>
  9. </li>
  10. </ul>
  11. </template>
  12. </card-com>
  13. </div>

子组件 <card-com>:

  1. <div class="card-com">
  2. <p class="title">
  3. <slot name="title"></slot>
  4. </p>
  5. <div class="content">
  6. <slot name="content"></slot>
  7. </div>
  8. </div>

渲染结构:

image.png

data-v-d1799a24 为父组件节点,data-v-060ff10e 为子组件节点,两个 id 都有的是插槽内的节点,子组件中对 .content 的样是会污染插槽中的 .content 节点。.content[data="data-v-060ff10e"] 匹配到了两个 .content 节点。

vuex 模块命名空间

store.js

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import hotPointRelate from './hotPointRelate'
  4. Vue.use(Vuex)
  5. export default new Vuex.Store({
  6. state: {},
  7. mutations: {},
  8. actions: {},
  9. modules: {
  10. hotPointRelate
  11. }
  12. })

hotPointRelate.js

  1. export default {
  2. namespaced: true,
  3. state: {
  4. dialogVisible: false
  5. },
  6. mutations: {
  7. // 弹框显示隐藏
  8. toggleDialog(state, v) {
  9. state.dialogVisible = v;
  10. }
  11. },
  12. actions: {}
  13. }

提交 mutation :

  1. this.$store.commit('hotPointRelate/toggleDialog', true);

使用 map 函数简化 带命名空间的绑定函数

  1. computed: {
  2. ...mapState('some/nested/module', {
  3. a: state => state.a,
  4. b: state => state.b
  5. })
  6. },
  7. methods: {
  8. ...mapActions('some/nested/module', [
  9. 'foo', // -> this.foo()
  10. 'bar' // -> this.bar()
  11. ])
  12. }

自动导入 vuex 模块

自动导入 ./module 文件夹下的所有 js 文件。require.context

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. const path = require('path')
  4. Vue.use(Vuex)
  5. const files = require.context("./modules", false, /\.js$/);
  6. const modules = {};
  7. files.keys().forEach(key => {
  8. const name = path.basename(key, '.js');
  9. modules[name] = files(key).default || files(key);
  10. // modules[key.replace(/(\.\/|\.js)/g, "")] = files(key).default;
  11. });
  12. export default new Vuex.Store({
  13. state: {
  14. },
  15. mutations: {
  16. },
  17. actions: {
  18. },
  19. modules
  20. })

自动导入 router

  1. // 导入路由
  2. const files = require.context("./routers", false, /\.js$/);
  3. const routes = [];
  4. files.keys().forEach(key => {
  5. routes.push(files(key).default);
  6. });
  7. export default new Router({
  8. routes,
  9. })

引入图片 作为变量

将打包前的图片路径作为变量,使用会有问题。

  1. <template>
  2. <img :src="imgUrl" />
  3. </template>
  4. <script>
  5. export default {
  6. data() {
  7. return {
  8. imgUrl: '../images/1.png'
  9. }
  10. }
  11. }
  12. </script>

可以用变量存打包后的图片路径。

  1. import imgUrl from '../images/1.png'
  2. let imgUrl = require('../images/1.png')

echarts 引入中国地区数据

  1. <script src="https://www.echartsjs.com/gallery/vendors/echarts/map/js/china.js"></script>
  1. import chinaJson from './china.json'

vue 引入 public 资源

放在 public 下的图片,通过相对路径引用,一样会被 webpack 打包。

  1. let imgUrl = require('../../public/1.png');
  2. console.log(imgUrl);
  3. // data:image/png;base64,iVBOR...

任何放置在 public 文件夹的静态资源都会被简单的复制,而不经过 webpack。你需要通过绝对路径来引用它们。 — vue cli

在 public/index.html 或其它通过 html-webpack-plugin 用作模板的 HTML 文件中,你需要通过 <%= BASE_URL %> 设置链接前缀。

在模板中,你首先需要向你的组件传入基础 URL:

  1. data () {
  2. return {
  3. publicPath: process.env.BASE_URL
  4. }
  5. }

然后:

  1. <img :src="`${publicPath}1.png`">

直接使用 process.env.BASE_URL 报错:

  1. <img :src="process.env.BASE_URL + '1.png'">

组件内部动态引入 public 文件夹下的 js,也可以使用此方法。

  1. let script = document.createElement('script')
  2. script.src = this.publicPath + 'a.js'
  3. // 引入 public/a.js

图片上传

使用 FormData 对象上传图片。

  1. <template>
  2. <input type="text" v-model="text"/>
  3. <input type="file" @change="saveFile" accept="image/*"/>
  4. <button @click="submit">submit</button>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. text: ''
  11. }
  12. },
  13. methods: {
  14. saveFile(e) {
  15. [].forEach.call(e.target.files, file => this.formFile.append('file', file))
  16. },
  17. submit() {
  18. this.formData.append('text', this.text);
  19. // submit();
  20. }
  21. },
  22. created() {
  23. this.formData = new FormData();
  24. }
  25. }
  26. </script>
  1. this.$axios.post('/upload', this.formFile, {
  2. method: 'post',
  3. headers: {
  4. 'Content-Type': 'multipart/form-data'
  5. }
  6. })

使用 axios 上传图片,遇到问题始终没法上传,发送请求,参数格式不对,formdata 对象的数据被转成了字符串,最终在拦截器里看到如下代码:

  1. axios.interceptors.request.use(config => {
  2. if (config.method === 'post') {
  3. config.data = qs.stringify(config.data) // post请求格式化数据
  4. config.headers['formdata'] = "1";
  5. }
  6. // ...
  7. });

使用 post 请求都被转成字符串了。将判断修改后:

  1. if (config.method === 'post' && Object.prototype.toString.call(config.data) !== '[object FormData]') {
  2. // ...
  3. }

ref 和 v-for 一起使用

当 ref 和 v-for 一起使用的时候,得到的引用将会是一个包含了对应数据源的这些子组件的数组,即使 ref 的值是唯一的,即使 v-for 遍历的数组长度为1。

  1. <template>
  2. <div v-for="item in list" :key="item.id">
  3. <custom-com ref="'customCom' + item.id"></custom-com>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. list: [
  11. {
  12. id: 'First'
  13. }
  14. ]
  15. }
  16. },
  17. mounted() {
  18. console.log(this.$refs.customComFirst);
  19. // 一个长度为1的数组
  20. }
  21. }
  22. </script>

监听子组件的生命周期

  1. <template>
  2. <child-component @hook:mounted="fn"></child-component>
  3. </template>

定时器离开页面后未关闭

  1. mounted() {
  2. setTimeout(this.init, 2000)
  3. }

如果在两秒内离开了当前路由,this.init 还是会被调用。

文件下载

  1. this.$axios.get('url', {
  2. params: {},
  3. responseType: 'blob'
  4. }).then(data => {
  5. const url = window.URL.createObjectURL(new Blob([data]));
  6. const a = document.createElement('a');
  7. a.style.display = 'none';
  8. a.href = url;
  9. a.setAttribute('download', 'filename');
  10. document.body.appendChild(a);
  11. a.click();
  12. window.URL.revokeObjectURL(a.href);
  13. document.body.removeChild(a);
  14. })

使用 EventBus 可能存在的问题

事件监听不会在组件销毁后自动移除。