修改组件父属性的值,是否使用 toRefs,在 composition api

Modifying value of component's parent properties, use toRefs or not, in composition api

我有一个组件的嵌套结构,其结构由嵌套数组定义。

当我想删除一个组件时,我需要访问驻留在父组件 props 上的父组件子数组变量,以便在那里找到组件并将其拼接出子数组。

{ 
  id:'p0',
  name:'parent',
  children:[
    { id:'p0c1-w4f5',name:'child1', children:[]},
    { id:'p0c2-wsad',name:'child2', children:[]},
  ]
}

child1 请求删除时,它会执行以下代码

const remove1 = (id) => {
  const instance = getCurrentInstance();
  const p = instance.parent;
  var p_children = p.props.children // <--- xxxxx without toRefs xxxxx
  var remove_index = null;
  p_children.forEach((e, index) => {
    if (e.id == id) {
      remove_index = index;
    }
  })
  p_children.splice(remove_index, 1)
}

或者我应该使用

const remove2 = (id) => {
  const instance = getCurrentInstance();
  const p = instance.parent;
  const { children } = toRefs(p.props) // <--- xxxxx with toRefs xxxxx
  var remove_index = null;
  children.value.forEach((e, index) => {
    if (e.id == id) {
      remove_index = index;
    }
  })
  children.value.splice(remove_index, 1)
}

两种方法都有效,但我想知道只使用第一种方法是否可以,以及为什么没有必要在父属性上使用 toRefs

const { children } = toRefs(p.props)

toRefs 如果您打算传递那个 children 变量或将其存储在某个地方以备将来使用并保持其反应性(因此当 parent 属性更改时, children 变量也会)。但是因为你没有做任何事情,所以根本不需要 toRefs...

否则我发现从 child 访问 parent props 很奇怪。我不喜欢它。恕我直言,更好的做法是将该逻辑移至 parent 并让 child 发出 parent 处理的事件。