Vue JS-在广告位中更改通过的道具

时间:2020-10-25 08:19:51

标签: vue.js vuejs2

我知道在Vue中更改道具很不好,但是,当您通过插槽传递道具时,我不确定这是否适用。 我有以下父组件,其中有一个插槽。

父项:

<template>
  <div>
    ..
    <slot :form="form"></slot>
    ..
  </div>
</template>
<script>
export default {
  name: 'parent-component',
  data () {
    return {
      form: new Form({
        fieldForParent: '',
        fieldForChild: '',
      })
    }
}
</script>

ChildComponent.vue

<template>
  <parent-component>
    <template v-slot = "{form}">
      <input v-model="form.fieldForChild" />
    </template>
  </parent-component>
</template>

对我来说,真正的困惑是应该将哪一个视为父母和孩子。基本上,ChildComponent.vue是组成父组件的组件,但它也将其值嵌套在父元素内。而且,API的数据是从父组件中获取的。

这是我的问题: 这是正确的做法吗?我这样做是为了可重用,因为子组件的多个实例将具有公共字段(因此父组件也是如此),但是每个子组件也将具有唯一的字段。请注意,在对子组件内的props进行更改后(通过更新input元素),我没有收到“避免直接对prop ..进行更改”警告。

1 个答案:

答案 0 :(得分:0)

让我先重新定义名称...实际上应该是这样

子组件

<template>
  <div>
    ..
    <slot :form="form"></slot>
    ..
  </div>
</template>
<script>
export default {
  name: 'parent-component',
  data () {
    return {
      form: new Form({
        fieldForParent: '',
        fieldForChild: '',
      })
    }
}
</script>

父组件

<template>
  <child-component>
    <template v-slot = "{form}">
      <input v-model="form.fieldForChild" />
    </template>
  </child-component>
</template>