vue3+elemlentplus使用总结

1. 深度监听

   开发过程中对列表的监听 即使监听到变化,但是获取到的新旧值是相同的,因为新旧值引用的是相同的响应式对象。代码如下:

watch(
  () => tableCData,
  (newValue, oldValue) => {
    if (newValue.length == 0 || !oldValue || oldValue.length == 0) {
      return;
    }
    if (newValue[0] != oldValue[0]) {  
      handleUpdeteC4OrC5();  // 这段逻辑不会走到
    }
  },
  { deep: true, immediate: true }
);

如果控制对列表某个属性的监听呢?

watch(
  () => tableCData.value.map((item) => item.C5),
  (newValue, oldValue) => {
    if (newValue.length == 0 || !oldValue || oldValue.length == 0) {
      return;
    }
    if (newValue[0] != oldValue[0]) { // 对第一行数据的C5属性监听
      handleUpdeteC4OrC5();
    }
  },
  { deep: true, immediate: true }
);

2. 全局样式使用

  a. 创建.css样式文件 如style.css

  b. 在main.js中引入

import "element-plus/dist/index.css"; // 引入 Element Plus 的样式 1

import "./style.css";  // 自定义全局样式类  2  1和2要严格按照顺序哦,不然就可能无法使用样式覆盖

3. 样式穿透

  全局样式中对elementplus组件样式做穿透直接对类进行编辑。如:

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

组件内部<style scoped></style>内,如果想对样式做穿透需要用 :deep 如:

:deep(.el-collapse-item__header) {
  font-size: 14px;
}

4. 回调子函数

  如果父组件需要调用子组件的场景该如何处理呢?

  比如子组件涉及到的校验,父组件在提交时需要对子组件的数据再校验一次,最简单的方法是父子组件中各维护一套校验逻辑,但是一旦需要更改逻辑 则父子组件中均需要更改比较繁琐。 通过definedExposed 将子组件的方法暴漏给父组件 可以实现父组件中对子组件方法的调用。

示例: 父组件:

<template>
 <ChildComponent ref="childRef" />
</template>
<script setup>
const childRef=ref()

// 调用暴露的方法
const handleClick = () => {
  childRef.value?.increment()
  console.log(childRef.value?.currentValue)
}
</script>

子组件:


defineExposed({
  increment: () => {return ++currentValue},
})

5. 组件间的数据传递  

  vu3通过pinia代替vue2的vuex进行状态管理

   a. npm install pinia

   b. 引入

import { createApp } from 'vue'
import { createPinia } from 'pinia'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')

  c. 核心使用

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    },
    async fetchData() {
      const res = await fetch('/api/data')
      this.data = await res.json()
    }
  }
})


//组件中
<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()
</script>

<template>
  <button @click="counter.increment">
    {{ counter.count }} ({{ counter.doubleCount }})
  </button>
</template>

d: 统一管理状态:

     可在store文件夹下创建 index.js   

export { useCounterStore } from "./counter";

     组件中:

import { useCounterStore } from "@/stores/index.js";

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值