前端(技巧+踩坑记录)

1、计算属性用法

2、map返回数据

3、过渡效果

移动端过渡: 

效果图:

 

 更多过渡效果:进入/离开 & 列表过渡 — Vue.js 

pc端过渡动画:

直接用el组件,自带过渡

4、el分页组件

5、svelte.js+vite使用sass 

5.1.下载依赖:

 svelte.config.js内:

import sveltePreprocess from 'svelte-preprocess'

export default {
  preprocess: [
    sveltePreprocess({
      scss: true
    })
  ]
}

5.2.将svelte.config.js放项目根目录即可

6、获取当前时间戳 及转换年月日时分秒格式为时间戳

// 1.获取当前时间戳

let currentTime = new Date().getTime()

// 2.转换年月日时分秒为时间戳
// this.detailData.questionnairePo.updateTime :"2022-07-20 14:46:43"

let questionDate = Date.parse(new Date(this.detailData.questionnairePo.updateTime))

7、字符串截取

拿前两位:name ? name.substring(2, -2) : '暂无' 

拿后两位:name? name.substring(name.length - 2, name.length)

8滚动条平滑置顶

  const doc = document.getElementById('scroll-box')

      doc.scrollTo({

        top: 0,

        behavior: 'smooth'

      })

9、文本超出换行

            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            display: -webkit-box;
            word-break: break-all;

有用的小技巧我会继续发

10、滚动条祛除

 找到滚动条的父类了,没有滚动条找到样式,解决方法:

// .f-menu为滚动条父类
.f-menu::-webkit-scrollbar {
  width: 0;
}

11、vue2报错解决

报错信息:
[Vue warn]: Error in nextTick: "NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."

DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node

 tip:弹框消失后,此vue组件就只剩下template,vue2模板必须要有个div

 12、el-tree搜索功能

这个方法是必写的不写报错:

filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }

 监听input内的值,值变了则改变树数据

  watch: {
    filterText(val) {
      console.log(val, 'val')
      this.$refs.tree.filter(val)
    }
  },

13、跨域的常用解决方法

13.1.cors

// request.js
 
import axios from 'axios'
 
const service = axios.create({
  withCredentials: true, //  跨域安全策略
  headers: {
    // 关键
    'Access-Control-Allow-Origin': '*'
  },
  timeout: 30 * 1000 // 超时时间 单位是ms
})
export default service

13.2.跨域代理

// vue.config.js
 
devServer: {
    // 设置为0.0.0.0则所有的地址均能访问
    host: '0.0.0.0',
    port: 8080,
    https: false,
    hotOnly: false,
    // 跨域问题解决 代理(关键部分)
    proxy: {
      '/api': {
        target: 'http://localhost:3000', // 注意!此处为后端提供的真实接口
        changeOrigin: true, // 允许跨域
        pathRewrite: {
          // 如果接口中是没有api的,那就直接置空,'^/api': '',
          // 如果接口中有api,那就得写成{'^/api':'/api'}
          '^/api': ''
        }
      }
    }
  }

14、让网页都在一个窗口内打开

 15、富文本数据渲染

let dom =document.getElementById('xxx') //xxx 为要插入富文本的元素
dom.innerHTML = 富文本数据

16、点击按钮复制文字

			copy(id) {
				let copycode = document.getElementById(id)
				const textarea = document.createElement('textarea');
				textarea.value = copycode.innerText;
				document.body.appendChild(textarea);
				textarea.select();
				document.execCommand('copy');
				document.body.removeChild(textarea);
			}

### 解决方案 在 Vue 中使用 `el-tabs` 切换时出现的 **NotFoundError** 报错通常是因为 DOM 节点被移除或未正确挂载的情况下尝试操作节点引起的。具体来说,错误提示: > Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. 表明某个 DOM 操作试图在一个不存在的父级节点下插入新节点。 以下是可能的原因及解决方案: #### 1. 动态组件销毁与重新创建 当 `el-tabs` 的内容依赖于动态组件(如懒加载),可能会因为组件卸载后再切换回原标签而导致 DOM 不匹配问题[^1]。可以通过设置 `keep-alive` 来缓存已加载的组件实例,从而避免频繁销毁和重建。 ```html <el-tabs v-model="activeName"> <el-tab-pane v-for="(item, index) in tabs" :key="index" :label="item.label" :name="item.name" > <!-- 使用 keep-alive 缓存 --> <keep-alive> <component :is="item.component"></component> </keep-alive> </el-tab-pane> </el-tabs> ``` #### 2. 异步更新引发的问题 如果 `el-tabs` 的切换触发了异步逻辑(例如 API 请求或其他耗时操作),可能导致 DOM 更新不同步而抛出异常。可以利用 Vue 的生命周期钩子来确保 DOM 已经完成渲染再执行后续操作。 ```javascript nextTick(() => { // 确保 DOM 渲染完成后才进行操作 someAsyncOperation(); }); ``` #### 3. 错误的事件绑定 某些情况下,`@tab-click` 或其他事件处理函数中可能存在不当的操作,比如手动修改 DOM 结构却未同步更新 Vue 数据模型。建议仅通过 Vue 提供的数据驱动方式管理视图变化。 #### 4. Tabs 内部结构破坏 确认是否有外部代码直接操纵了 `el-tabs` 所属范围内的 HTML 元素。任何绕过框架的行为都容易引起不可预测的结果。务必遵循官方文档推荐的最佳实践[^2]。 --- ### 示例修复代码 下面是一个综合考虑以上几点后的改进版本: ```vue <template> <div> <el-tabs v-model="activeTab" @tab-change="handleTabChange"> <el-tab-pane label="用户管理" name="users"> <UserManagement /> </el-tab-pane> <el-tab-pane label="配置管理" name="settings"> <Settings /> </el-tab-pane> </el-tabs> </div> </template> <script setup> import { ref, nextTick } from "vue"; import UserManagement from "./components/UserManagement.vue"; import Settings from "./components/Settings.vue"; const activeTab = ref("users"); function handleTabChange(tabName) { console.log(`Switched to tab: ${tabName}`); // 延迟执行潜在影响DOM的任务 nextTick(() => { initializeTabContent(tabName); }); } async function initializeTabContent(name) { try { if (name === "users") { await fetchUserData(); // 替代实际业务方法 } else if (name === "settings") { await loadConfigurations(); } } catch (error) { console.error("Failed initializing content:", error.message); } } </script> ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值