浅析 Vue3 setup

322 阅读1分钟

在Vue3中,setup只会在组件初始化的时候执行一次,所以,当我们在内部使用setinterval等去改变属性是没用的

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  setup (props, { slots, attrs, emit }) {
    let name = 1
    setInterval(() => {
      name += 1
    }, 1000)
    return {
      name
    }
  }
})
</script>
  • rective 我们可以通过reactive来实现数据响应式
<script lang="ts">
import { defineComponent, reactive } from 'vue'

export default defineComponent({
  setup (props, { slots, attrs, emit }) {
    const state = reactive({
      name: 1
    })
    setInterval(() => {
      state.name += 1
    }, 1000)
    return {
      state
    }
  }
})
</script>

setup内部 return时,不能使用类似{...state}的语法,因为结构以后,那个值就不是响应式的了

  • ref
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'

export default defineComponent({
  setup (props, {
    slots,
    attrs,
    emit
  }) {
    const nameRef = ref(1)
    setInterval(() => {
      nameRef.value += 1
    }, 1000)
    return {
      name: nameRef
    }
  }
})
</script>
  • 计算属性
<script lang="ts">
import { defineComponent, reactive, ref, computed } from 'vue'

export default defineComponent({
  setup (props, {
    slots,
    attrs,
    emit
  }) {
    const nameRef = ref(1)
    const computedNameRef = computed(() => {
      return nameRef.value + 1
    })
    setInterval(() => {
      nameRef.value += 1
    }, 1000)

    return {
      name: nameRef,
      name2: computedNameRef
    }
  }
})
</script>
  • watchEffect watchEffect类似react中的useEffect,但是它不用去声明监听哪些值的变化,只要是其内部的值变了,他就会执行
    watchEffect(() => {
      console.log(nameRef.value)
    })

只会在 nameRef 改变时,触发log