父组件中通过v-model来显示子组件

方法一

父组件示例:

<operationRecord v-model="displayRecord" ></operationRecord>

子组件示例:

<template>
  <div>
    <Modal v-model="opreate" width="1100" footer-hide @on-cancel="labelCancel">
      <Table :border="true" :columns="header"  :data="recordData"></Table>
    </Modal>
  </div>
</template>

<script>
  export default {
    props: {
      value: {
        type: Boolean,
        default: false,
      },
      recordData:{
        type: Array,
        default: () => [],
      }
    },
    watch: {
      value(newValue, old) {
        this.opreate = newValue
      }
    },
    data(){
      return {
        opreate: false,
        header: [
          { title: "序号", type: "index", align: "center", width: 80 },
          { title: "操作时间", key: "time", align: "center", minWidth: 200 },
          { title: "操作人员", key: "user", align: "center", minWidth: 200 },
        ],
      }
    },
    methods:{
      labelCancel(){
        this.$emit('input', false) // 关闭弹框
      }
    }
  }
</script>

方法二

 父组件示例:

<add-or-update :isShow.sync="isShow" ></add-or-update>

子组件示例:

  props: {
    isShow: {
      type: Boolean,
      default: false,
    }
  }
  computed: {
    show: { // 它是子组件内部,绑定的v-model值
      get() {
        return this.isShow;
      },
      set(val) {
        this.$emit("update:isShow", val);
      },
    }
  }
  
this.show = false   // 直接操作就可以了

总结

`:isShow.sync`

  • 这是一种自定义的 prop,通常在子组件中使用。
  • 它需要在子组件的 props 中声明,同时需要在父组件中使用 .sync 修饰符进行绑定。
  • 当子组件需要修改这个值时,它应该通过 this.$emit('update:isShow', newValue) 的方式通知父组件,父组件会响应这个事件来更新 isShow
  • 这样的绑定方式有助于明确表达数据的双向绑定,但需要更多的代码来实现。

`v-model`:

  • v-model 是一种更简洁的语法糖,通常在子组件中不需要额外的声明,只需在子组件中使用 model 选项进行配置。
  • 它是基于 value prop 和 input 事件进行工作的,父组件只需使用 v-model 来绑定数据即可。
  • 当子组件需要修改这个值时,它只需直接修改 this.$emit('input', newValue),父组件会自动更新 v-model 绑定的值。

总的来说,使用 v-model 更简洁,但在子组件中需要额外的配置 model 选项。

使用 :isShow.sync 更明确,需要在父组件中使用 .sync 修饰符,但无需额外的配置。

你可以根据项目的需求和你更喜欢的语法风格来选择其中之一。 

猜你喜欢

转载自blog.csdn.net/weixin_48674314/article/details/134298563