当前位置: 代码迷 >> 综合 >> setup参数
  详细解决方案

setup参数

热度:99   发布时间:2023-09-20 15:35:27.0

参数一:props

* setup 可以接收props为父组件的传值的props

 * 如果props里的msg为必须项,可以通过 let {msg} = toRefs(props)进行解构赋值

 * 如果msg为非必须项可以通过 let msg = toRef(props,'msg')进行创建msg

<template><div>{
   { msg }}</div>
</template><script>import { ref } from 'vue'export default {name: 'HelloWorld',props: {msg: {type:String,require: true}},setup (props) {// props中msg为必须项let { msg } = toRefs(props)// props中msg为可选项let msg =  toRef(props,'msg')return {msg}}
}
</script>

 setup参数二:context

 * context.attrs:Attribute (非响应式对象,等同于 $attrs),会随着改变而改变要避免结构,使用attrs.x
 * context.slots:插槽 (非响应式对象,等同于 $slots),会随着改变而改变要避免结构,使用slots.x
 * context.emit:触发事件 (方法,等同于 $emit)
 * context.expose: 暴露公共 property (函数)
 * context是一个非响应式对象,可以使用es6解构赋值
 * attrs,slots property 为非响应式 更改应用副作用,那么应该在 onBeforeUpdate 生命周期钩子中执行此操作

 使用渲染函数

import { h } from 'vue',该函数可以直接使用在同一作用域中声明的响应式状态

<template><div>123</div>
</template><script>import { ref, h } from 'vue'export default {name: 'HelloWorld',props: {},setup () {let count = ref(0);return () => h('div', count.value)}
}
</script>

  相关解决方案