学习工具(方便、无需自己搭建环境)

Vue SFC Playground :https://sfc.vuejs.org/

image.png

setup

setup是组合Composition API中的入口函数,也是第一个要使用的函数。

setup只在初始化时执行一次,所有的Composition API函数都在此使用。

生命周期

setup执行在beforeCreate和created之前

<template>
<div class="container">
</div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, onMounted } from 'vue'
export default defineComponent({
  name: 'App',
  beforeCreate () {
    console.log('beforeCreate')
  },
  created () {
    console.log('created')
  },
  setup () {
    console.log('setup')
    onBeforeMount(() => {
      console.log('onBeforeMount')
    })
    onMounted(() => {
      console.log('onMounted')
    })
  }
})
</script>

image.png

可以推断出setup执行的时候,组件对象还没有创建,组件实例对象this还不可用,此时thisundefined, 不能通过this来访问data/computed/methods/props

父子组件生命周期

  1. 子组件onMounted 在父组件之前
  2. 子组件onUpdated 在父组件之前

父组件

<template>
<div class="container">
 父组件-->{{msg}}
 //子组件
<ChildItem :msg="msg" :msg1="msg1"></ChildItem>
</div>
</template>


<script lang="ts">
import { defineComponent,ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from 'vue'
import ChildItem from './components/base/Child.vue'
export default defineComponent({
  name: 'App',
  components: {
    ChildItem

  },
  beforeCreate () {
    console.log('父beforeCreate')
  },
  created () {
    console.log('父created')
  },
  setup () {
    console.log('父setup')
    onBeforeMount(() => {
      console.log('父onBeforeMount')
    })
    onMounted(() => {
    //更新数据
    setTimeout(() => {
        msg.value = 'hello,1s后修改msg'
        console.log('msg 被修改')
      }, 1000)
      console.log('父onMounted')
    })
    onBeforeUpdate(() => {
      console.log('父onBeforeUpdate')
    })
    onUpdated(() => {
      console.log('父onUpdated')
    })
  }
})
</script>

Child.vue

<template>
  <div>子组件-->{{msg}}</div>

</template>

<script lang="ts">
import { defineComponent, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from 'vue'

export default defineComponent({
  name: 'ChildItem',
  props: {
    msg: {
      type: String,
      required: true
    }
  },
  beforeCreate () {
    console.log('子beforeCreate')
  },
  created () {
    console.log('子created')
  },
  setup (props, { attrs, slots, emit }) {
    console.log('子setup')
    onBeforeMount(() => {
      console.log('子onBeforeMount')
    })
    onMounted(() => {
      console.log('子onMounted')
    })
    onBeforeUpdate(() => {
      console.log('子onBeforeUpdate')
    })
    onUpdated(() => {
      console.log('子onUpdated')
    })
  }

})
</script>


image.png

Logo

前往低代码交流专区

更多推荐