Vue3组合式API-模版引用示例(获取组件对象)

App.vue组件:

<script setup>
import Son from './components/son.vue'
import { onMounted, ref } from 'vue'

const comRef = ref(null)

// 组件挂载完毕之后才能获取
// onMounted函数在组件挂载完成后执行
onMounted(() => {
  console.log(comRef.value)
})
</script>

<template>
  <!-- 通过ref属性绑定ref对象 -->
  <Son ref="comRef"></Son>
</template>

<style scoped></style>

子组件son.vue:

<script setup>

</script>

<template>
    <div class="son">
        <div>我是子组件</div>
    </div>
</template>

<style scoped></style>

在浏览器中查看结果:
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,组合式API可以与v-for指令一起使用,以动态生成组件、列表和其他内容。 首先,我们需要在组件中导入`reactive`和`computed`函数。然后,我们可以使用`reactive`创建一个响应式状态对象,并在`computed`函数中使用它来生成动态内容。最后,我们可以使用v-for指令将内容渲染为列表。 以下是一个使用组合式API和v-for指令的简单示例: ```html <template> <div> <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> </div> </template> <script> import { reactive, computed } from 'vue'; export default { setup() { const state = reactive({ items: [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' }, ], }); const filteredItems = computed(() => { return state.items.filter((item) => { return item.text.includes('2'); }); }); return { items: filteredItems, }; }, }; </script> ``` 在上面的示例中,我们使用`reactive`创建一个响应式状态对象`state`,其中包含一个名为`items`的数组。然后,我们使用`computed`函数创建一个名为`filteredItems`的计算属性,该属性根据特定条件过滤`items`数组中的元素。 最后,我们将`filteredItems`作为组件的输出,然后在模板中使用v-for指令将其渲染为一个列表。在此示例中,我们只渲染了包含数字2的项目。 请注意,由于组合式API使用`setup`函数而不是传统的`data`和`computed`选项,因此我们需要使用不同的语法来定义状态和计算属性。同时,我们也需要使用不同的方式将它们暴露给模板。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值