vue3遇到问题集合

  1. Vue3组件中getCurrentInstance()获取App实例,但是返回null
    getCurrentInstance()、useStore 、 useRouter 只能写到setup函数里面,不能套在别的函数里面使用
<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';

// 获取当前组件实例
const { appContext } = getCurrentInstance();
</script>
  1. setup语法通过defineProps获取props为null,在setup()里面获取为空,但在<script setup>可以获取
  • defineProps 只能在 setup 中使用,且只能在 setup 的顶层使用,不能在局部作用域使用
  • defineProps 里的属性只读,不能修改
  • defineProps 是 vue3 的一个宏函数,不需要导入就可以直接使用
  • defineProps 函数返回一个对象,是一个 proxy ,所有的特性和 reactive 基本相同,可以直接在模版上进行使用

原因需要传值:
setup()两个参数:
1.props:值为对象,包含:组件外部传递过来。切组件内部声明接收了的属性

2.context :上下文对象

attrs:值为对象,包含组件外部传递过来,但没有在props配置中声明的属性。相当于this. a t t r s s l o t s :收到的插槽内容,相当于 t h i s . attrs slots:收到的插槽内容,相当于this. attrsslots:收到的插槽内容,相当于this.slots
emit:分发自定义事件的函数,相当于this.$emit

注意:需要将接收的props作用在setup的顶层,不能放到setup生命周期里面(defineProps 第1点)
解决方式如下:

export default{ 
    props: {  
        msg: String,  
        ans: String, 
    }, 
    setup(props,context){  
        console.log(props);
    },
}
<script setup>
// defineProps 返回一个对象,可以定义任意的变量去接收这个对象

// 方式1: 以对象的形式去接收
const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    isEdit: {
        type: Boolean,
        default: false,
    }
});
// 方式2: 以数组的方式去接收
const childProps = defineProps(['show', 'isEdit'])
</script>
  1. 控制台报错onMounted is called when there is no active component
    解决方式 将onMounted 放到其他函数或调用前面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值