本人刚接触vue3组合式api开发,很多不熟悉的地方请多指教。
在开发一个项目时,涉及到父子组件传参的问题,由于对vue3不熟练,参考前辈的项目进行开发。但在子组件接受父组件传值的时候发现了问题,直接上代码。
<script setup>
import { ref, nextTick, reactive, defineProps, defineEmits } from 'vue';
const props = defineProps(["resonName"]);//接受父组件传过来的“resonName”参数
//获取详情
const getNegativeReviews = async () => {
console.log('props.resonName', props.resonName);//这里能打印出父组件传过来的值
};
getNegativeReviews();//通过这种方式调用是可以拿到父组件传过来的resonName参数的
</script>
getNegativeReviews函数这是页面数据的初次请求,getNegativeReviews()直接在setup中调用是可以通过props.resonName方式拿到父组件传过来的值的
接下来问题出现了,当我需要在页面上通过点击事件触发函数时,出现了undefine情况。
<template>
<div class="operate" @click="toShowDetail()">
<div>月度趋势</div>
<div class="arrowDown"></div>
</div>
</template>
<script setup>
import { ref, nextTick, reactive, defineProps, defineEmits } from 'vue';
const props = defineProps(["resonName"]);//接受父组件传过来的“resonName”参数
//获取详情
const getNegativeReviews = async () => {
console.log('props.resonName', props.resonName);//这里能打印出父组件传过来的值
};
getNegativeReviews();//通过这种方式调用是可以拿到父组件传过来的resonName参数的
const toShowDetail = () => {
console.log('props.resonName', props.resonName);//这里通过点击事件打印出来的是undefined
}
</script>
在网上百度了很多都找不到合理的解释,后来自己用了赋值的方式解决。
const resonName = props.resonName;
<template>
<div class="operate" @click="toShowDetail()">
<div>月度趋势</div>
<div class="arrowDown"></div>
</div>
</template>
<script setup>
import { ref, nextTick, reactive, defineProps, defineEmits } from 'vue';
const props = defineProps(["resonName"]);//接受父组件传过来的“resonName”参数
const resonName = props.resonName;//把props中的值赋给resonName
//获取详情
const getNegativeReviews = async () => {
console.log('props.resonName', props.resonName);//这里能打印出父组件传过来的值
};
getNegativeReviews();//通过这种方式调用是可以拿到父组件传过来的resonName参数的
const toShowDetail = () => {
console.log('props.resonName', resonName);//这样就可以拿到父组件传过来的值了
}
</script>
虽然问题解决了,但还是不明白其中的原理,有没有哪位大佬能给新手小白解释一下