- Vue3组件中getCurrentInstance()获取App实例,但是返回null
getCurrentInstance()、useStore 、 useRouter 只能写到setup函数里面,不能套在别的函数里面使用
<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
// 获取当前组件实例
const { appContext } = getCurrentInstance();
</script>
- 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>
- 控制台报错onMounted is called when there is no active component
解决方式 将onMounted 放到其他函数或调用前面