ITPub博客

首页 > 移动开发 > HTML5 > Vue3组合式API——setup细节

Vue3组合式API——setup细节

原创 HTML5 作者:灬青芒灬 时间:2023-07-27 16:35:11 0 删除 编辑
  • setup执行的时机

    • 在beforeCreate之前执行(一次), 此时组件对象还没有创建

    • this是undefined, 不能通过this来访问data/computed/methods / props

    • 其实所有的composition API相关回调函数中也都不可以

  • setup的返回值

    • 一般都返回一个对象: 为模板提供数据, 也就是模板中可以直接使用此对象中的所有属性/方法

    • 返回对象中的属性会与data函数返回对象的属性合并成为组件对象的属性

    • 返回对象中的方法会与methods中的方法合并成功组件对象的方法

    • 如果有重名, setup优先,现在是报错了

    • 注意:

      • 一般不要混合使用: methods中可以访问setup提供的属性和方法, 但在setup方法中不能访问data和methods

      • setup不能是一个async函数: 因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性数据

  • setup的参数

    • setup(props, context) / setup(props, {attrs, slots, emit})

    • props: 包含props配置声明且传入了的所有属性的对象

    • attrs: 包含没有在props配置中声明的属性的对象, 相当于 this.$attrs

    • slots: 包含所有传入的插槽内容的对象, 相当于 this.$slots

    • emit: 用来分发自定义事件的函数, 相当于 this.$emit

<!--App父级组件-->
<template>
  <h2>App父级组件,setup的细节</h2>
  <h3>msg:{{msg}}</h3>
  <button @click="msg+='==='">更新数据</button>
  <Child :msg="msg" msg5="测试" @xxx="xxx" />
</template>
<script>
import { defineComponent, ref } from 'vue'
import Child from './components/Child.vue'
export default defineComponent({
  name: 'App',
  // 注册组件
  components: {
    Child
  },
  setup() {
    // 普通类型的响应式数据
    const msg = ref('what are you no sha lei')
    // 更新普通数据
    const xxx = (txt:string) => {
      msg.value += txt
    }
    return {
      msg,
      xxx
    }
  }
})
</script>
<!--Child子级组件-->
<template>
  <h3>Child子级组件</h3>
  <h3>父级传过来的msg:{{msg}}</h3>
  <button @click="updateParentMsg1">修改父级组件中的数据</button>
</template>
<script>
// 引入定义组件的api
import { defineComponent } from 'vue'
// 定义组件并暴露
export default defineComponent({
  name: 'Child',
  props: ['msg'],
// props仍然是一个代理对象,内部有父级组件向子级组件传递进来的数据
// props参数中的数据是否存在,要看当前的子级组件是否曾经使用props进行接收
// 父级组件传入进来的数据,第一要通过props进行接收,虽然接收了,数据在组件的实例对象中,但是setup执行的时候,内部是没有this的
// console.log(props)
// context中有attrs对象,存储的是父级组件向子级组件传入进来的数据,但是这个数据没有使用props进行接收,相当于vue2.x中的this.$attrs属性
// console.log(context)
// context.emit('xxx','嘎嘎')
// console.log('setup执行了',this) // this是undefined,原因:setup执行的时候,组件实例对象还没创建
  setup(props, context) {
    // 用来获取父级组件传递过来的数据,需要子级组件使用props进行接收
    console.log(props.msg)
    // 用来获取父级组件传递过来的数据,没有使用props接收的数据
    console.log(context.attrs.msg1)
    // 按钮点击事件的回调函数,内部分发父级组件传递过来的自定义事件
    const updateParentMsg1 = () => {
      context.emit('updateMsg', '真香啊')
    }
    return {
      updateParentMsg1
    }
  }
})
</script>


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69917895/viewspace-2966807/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2023-03-30

  • 博文量
    7
  • 访问量
    2854