vue3使用日志


使用 <script setup> 的组件如何暴露属性

可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性:

<script setup>
import { ref } from 'vue'

const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

当父组件通过模板引用的方式获取到当前组件的实例,获取到的实例会像这样 { a: number, b: number } (ref 会和在普通实例中一样被自动解包)

实战案例

父组件页

<Scroll class="index-list" @scroll="onScroll" :probe-type="3" ref="scrollRef">
......
<script setup>
  const { shortcutList, scrollRef, onShortcutTouchStart, onShortcutTouchMove } =
 useShortcut(props, groupRef);    
</script>

https://gitee.com/chunsuo/suoMusic/blob/master/src/components/base/index-list/index-list.vue
逻辑抽离页

const scroll = scrollRef.value.scroll;
scroll.scrollToElement(targetEl, 0);

https://gitee.com/chunsuo/suoMusic/blob/master/src/components/base/index-list/use-shortcut.js
子组件页

...... // 一些代码
const scroll = useScroll(rootRef, props, emits);
// 使用defineExpose将属性暴露
defineExpose({
  scroll
});

https://gitee.com/chunsuo/suoMusic/blob/master/src/components/base/scroll/scroll.vue
子组件逻辑抽离页

export default function useScroll(wrapperRef, options, emits) {
    const scroll = ref(null);  // scroll将会在逻辑代码中绑定一个插件实例
    ..... // 一些逻辑代码
    return scroll; // return实例
}

https://gitee.com/chunsuo/suoMusic/blob/master/src/components/base/scroll/use-scroll.js


文章作者: ycs
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ycs !
  目录