ref的用法:
//子组件 <template> <div class="son">我是子组件{{num}}</div> </template> <script> imoprt ref from 'vue' let num = ref(100) //这里需要注意:组件内部数据对外是关闭的,如果想让外部访问需要通过defineExpose的方法对外暴露 defineExpose({num}) </script>
子组件若想获取父组件的值,需要用到$parent:
//子组件 <template> <div class="son" @click="handler($parent)">我是子组件{{num}}</div> </template> <script> imoprt ref from 'vue' let num = ref(100) handler=($parent)=>{ console.info($parent) } </script>
<template> <h1>我是父组件{{num}}</h1> <Son ref="son"></Son> </template> <script> import Son fron './son.vue' imoprt ref from 'vue' let num = ref(10000) let son = ref() //这里需要defineExpose的方法对外暴露,子组件才可以获取到 defineExpose({num}) </script>
需注意的是:
组件内部数据对外是关闭的,如果想让外部访问需要通过defineExpose的方法对外暴露