Vue使用ref属性代替props


前言

学过vue的小伙伴应该都知道,父子组件通信一般使用props,下面我们使用ref代替props来实现一个弹窗功能


一、父组件

<template>
  <div>
    <el-button type="primary" @click="handleOpen">打开弹窗</el-button>

    <!--    弹窗-->
    <son-model ref="model"></son-model>
  </div>
</template>

<script>
import sonModel from "@/components/sonModel";

export default {
  name: "Father",
  components:{
    sonModel
  },
  methods:{
    handleOpen(){
      // 通过ref拿到弹窗组件,然后直接调用弹窗组件的open方法
      this.$refs.model.open()
      // 修改弹窗组件的title
      this.$refs.model.title = '弹窗①号'
    }
  }
}
</script>

<style scoped>

</style>

二、子组件

<template>
  <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%">
    <span>这是一段信息</span>
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </span>
  </el-dialog>
</template>
<script>
export default {
  name: "sonModel",
  data(){
    return {
      dialogVisible: false,
      title:'',
    }
  },
  methods:{
    // 打开弹窗
    open(){
      this.dialogVisible = true
    },
    handleSubmit(){
     // 做一些提交的逻辑操作

      this.dialogVisible = false
    },
    handleCancel(){
      this.dialogVisible = false
    }
  },
}
</script>

<style scoped>

</style>

总结

巧妙的使用ref可以简化我们的代码。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3.2中,如果你使用watch监听props属性,会出现这样的警告: ``` [Vue warn]: Property "xxx" was accessed during render but is not defined on instance. at <ChildComponent onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< null > > at <ParentComponent> ``` 这是因为Vue3.2对props的处理方式有所改变,导致watch监听props时会出现警告。解决这个问题的方法有两种: 1. 使用watchEffect代替watch Vue3.2中引入了新的API——watchEffect,它可以自动追踪响应式数据的变化,并在变化时执行回调函数。因此,你可以使用watchEffect来代替watch监听props属性: ``` import { watchEffect } from 'vue'; export default { props: { xxx: { type: String, default: '' } }, setup(props) { watchEffect(() => { console.log(props.xxx); }); } }; ``` 2. 使用provide/inject传递props 另一种解决方法是使用provide/inject来传递props属性。在父组件中使用provide来提供props属性,然后在子组件中使用inject来注入props属性。这种方法可以避免watch监听props时出现的警告。 ``` // ParentComponent.vue <template> <ChildComponent :xxx="xxx" /> </template> <script> import { provide } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { xxx: 'xxx' }; }, setup() { provide('xxx', this.xxx); } }; </script> // ChildComponent.vue <script> import { inject } from 'vue'; export default { setup() { const xxx = inject('xxx'); console.log(xxx); } }; </script> ``` 这两种方法都可以解决watch监听props属性时出现的警告。你可以根据自己的实际情况选择其中一种方法来使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值