javascript Vue3从另一个组件调用组件方法

1l5u6lss  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(226)

我试图让一个组件调用另一个组件的函数,但只是在安装程序内部。我从vuemastery https://www.vuemastery.com/blog/understanding-vue-3-expose/读到这个,我看到你可以这样完成:

methods: {
    reset () {
      this.$refs.counter.reset()
    },
    terminate () {
      this.$refs.counter.terminate()
    }
  }

但是,我无法在安装程序中访问这些方法,而且我也无法在安装程序中使用这个.$refs。是否有方法可以在安装程序中执行相同的操作,或者有方法可以在安装程序中访问这些方法?
这些方法在setup中未定义,我无法从这些函数中访问数据setup,也无法在setup中使用$refs。
$refs是一种从另一个组件调用函数的非常简单的方法--但是我似乎找不到一种相对简单的方法来使用vue 3组合API --我错过了什么吗?

tyu7yeag

tyu7yeag1#

嘿我想出来了https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs
如果我走了

<script>
 export default {
  setup(props) {
   const counter = ref(null);
   //now I have access to counter.value.reset after it's mounted
   counter.value.reset(); //does not work! it's null here
   onMounted(() => {
    counter.value.reset(); //here it works
   })
   //make sure to return counter in return

看起来有一个简单的方法来做到这一点,在安装只是有一个警告

我是在触发器上调用它的-因此,如果有人从下拉列表中选择某个内容,我会观察V模型,并能够在那里调用它,没有问题。感谢所有输入。将此答案放在此处,以防其他人需要完成相同的事情

相关问题