VUE 3.0 抛弃基于类的API,采用基于函数的方法

Vue团队宣布即将到来的Vue 3提出的基于功能的组件API。与React hook一样,基于功能的组件API也允许开发人员将逻辑封装到所谓的“组合函数”中,并在组件之间重用逻辑。此外,新的组件API将提供更好的内置TypeScript类型推断支持,这是现在废弃的类API RFC所不能提供的。Vue 3的新API不会替代现有的Vue 2组件API,而是与现有的Vue 2组件API并存。

import { state, value, computed, watch } from '@vue/observer'

// reactive object
// equivalent of 2.x Vue.observable()
const obj = state({ a: 1 })

// watch with a getter function
watch(() => obj.a, value => {
  console.log(
`obj.a is: 
${
value
}
`
)
})

// a "pointer" object that has a .value property
const count = value(0)

// computed "pointer" with a read-only .value property
const plusOne = computed(() => count.value + 1)

// pointers can be watched directly
watch(count, (count, oldCount) => {
  console.log(
`count is: 
${
count
}
`
)
})

watch(plusOne, countPlusOne => {
  console.log(
`count plus one is: 
${
countPlusOne
}
`
)
})

import { onMounted, onUpdated, onDestroyed } from 'vue'

export default {
  created() {
    onMounted(() => {
      console.log('mounted')
    })

    onUpdated(() => {
      console.log('updated')
    })

    onDestroyed(() => {
      console.log('destroyed')
    })
  }
}
function useMouse() {
  const x = value(0)
  const y = value(0)
  const update = e => {
    x.value = e.pageX
    y.value = e.pageY
  }
  onMounted(() => {
    window.addEventListener('mousemove', update)
  })
  onUnmounted(() => {
    window.removeEventListener('mousemove', update)
  })
  return { x, y }
}
function useFetch(props) {
 const isLoading = value(true)
 const post = value(null)
 
 watch(() => props.id, async (id) => {
   isLoading.value = true
   post.value = await fetchPost(id)
   isLoading.value = false
 })
 
 return {
   isLoading,
   post
 }
}



import { createComponent } from 'vue'

const MyComponent = createComponent({
  // props declarations are used to infer prop types
  props: {
    msg: String
  },
  setup(props) {
    props.msg // string | undefined

    // bindings returned from setup() can be used for type inference
    // in templates
    const count = value(0)
    return {
      count
    }
  }
})

你可能感兴趣的:(IT生活,研发圈)