vue3 使用中遇到的特殊细节

94 阅读1分钟

1. 不需要解包

使用defineExpose({})时,无论ref还是parent在取值时,都不用.value,直接去取值就行

template中,通过 $parent 去取;在setup页面中,parent通过一下代码去取即可

import { getCurrentInstance } from 'vue';

const instance = getCurrentInstance();
const parent = instance?.proxy?.$parent;

2. provide inject

provide&inject 相对于 $attr的优势是 不用在每个组件都进行传值,直接在任意需要通信的两个组件去写即可

provide不能写到函数里面,写在setup页面即可。

inject在取值时,也不用监听,在setup页面中直接通过.value去取值。

3. 计算属性の传参

Vue中计算属性不可以接受参数,但是可以通过闭包的形式,返回出去一个函数,来实现在计算属性中传递参数。

  <td v-for="(cell, colIndex) in row">
   {{ data(cell) }}
  </td>

   const data =computed(()=>{
      // 通过闭包的形式,在计算属性里传递参数
      return (cell)=>{
        if(cell.func.length>0) {
          if(cell.func.includes("sum")) {
            return 'sum'
          }else if(cell.func.includes("average")) {
            return 'average'
          }
        }else {
             return cell.content 
        }
      
      }
    })

通过以上的方式就可以实现在计算属性中传递参数了。