vue中的.sync修饰符配合$emit(update:××)使用

950 阅读1分钟

如果写组件的显示和隐藏个人感觉修饰符.sync修饰符配合$emit(update:××)使用更适合。
直接上代码

父组件
<template>
  <div @click="handleShow">
     <!-- 引入子组件 -->
    <the-search :isShow.sync="isShowSearch"></the-search>
  </div>
</template>

<script>
improt TheSearch from './TheSearch.vue'
export default {
  name: 'Home',
  components: {
    TheSearch
  },
  data:(){
    return{
      isShowSearch:false
    }
  },
  methods:{
    handleShow(){
      this.isShow = true
    }
  }
}
</script>
子组件
<template>
  <div v-if="isShow">
    <button @click="handleClose">关闭</button>
  </div>
</template>
<script>
export default {
  name: 'TheSearch',
  props:['isShow'],
  methods: {
    handleClose(){
      this.$emit('update:isShow',false)
    }
  }
}
</script>

详细了解

父组件中引入子组件 TheSearch
<the-search :isShow.sync="isShowSearch"></the-search>
相当于
<the-search :isShow="isShow" @update:isShow="isShowSearch"></the-search>

如果使用的是Vue3 就沒有.sync什麼事了,因為Vue完全去掉了.sync 同統一使用 v-model 如果要绑定属性名, 只需要给v-model传递一个参数就行, 同时可以绑定多个v-model:

<modal v-model:visible="isVisible" v-model:content="content"></modal>

<!-- 相当于 -->
<modal
    :visible="isVisible"
    :content="content"
    @update:visible="isVisible"
    @update:content="content"
/>

哪位大佬有更好的方法,欢迎留言!