事先说明
- 使用的是 vue3 的 setup 语法糖
- 仅在 H5 和微信小程序测试过,其他端没试过但应该差不多
- 环境如下
- HBuildx v3.96
- 微信开发者工具 v1.06.2308310
- 谷歌浏览器 v119.0.6045.124
- Microsoft Edge版本v119.0.2151.44 (正式版本) (64 位)
直接上实例
父组件 index.vue
<template>
<text>父组件内容 = {{ count }} </text>
<button type="default" @click="add">+1</button>
<test ref="myTest" />
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import Test from './Test.vue'; // 引入子组件
const count = ref<number>(0);
// const myTest= ref(null); // 此处填入null或者不填都行,至少我这边试了留空也行
const myTest= ref();
const add = () => {
count.value += 1;
// 此处调用子组件的方法
myTest.value.add2(1); // 此处是vue3的ref切记要 .value
// vue2是 this.$refs.myTest.add2(1);
// 转变为vue3 则是 myTest.value.add2(1);
};
</script>
子组件 Test.vue
<template>
<view class="box">
<view class="btn">
<button type="default" @click="add2(1)">+1</button>
<text>子组件:{{ count }}</text>
<button type="default" @click="add2(-1)">-1</button>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const count = ref<number>(0);
const add2 = (num: number) => {
count.value += num;
};
// 重点:此处一点要对外暴露 不然外部无法使用,当做是js的module的export即可
defineExpose({ add2 });
</script>
<!-- 简单样式可有可无 不是重点-->
<style scoped lang="scss">
.box {
width: 90vw;
padding: 20rpx;
margin: 20rpx auto;
background-color: #efefef;
border: 1rpx solid gray;
.btn {
display: flex;
}
}
</style>
补充说明
- 这是我重构项目时遇到的一个点,vue2升vue3,但是项目中使用了很多的ref
- 关于是否原创,那肯定不可能是原创的,但是投稿只有【原创、转载、翻译】这三项,【转载、翻译】怎么感觉都不是,因为是自己写的所以就默认【原创】投稿了。反正都是直接百度或者看官方文档的,相同的内容肯定csdn都有,但是内容杂乱。
- 我发博客只是为了记录,现在感觉开始忘记东西了,为了往后回首还能看到自己花时间的东西,姑且记录下