没办法抛弃 ie,又希望能体验下 composition-api,可以来试试我写的
发布于 3 年前 作者 clubadmin 1982 次浏览 来自 问答
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

注意:不兼容官方的 [@vue/composition-api](https://composition-api.vuejs.org/)

纯 vue2 代码实现的 [@zhengxs2018/composition-api](https://github.com/zhengxs2018/composition-api),不依赖 ES6 的 Proxy 对象, 轻量,无依赖。

对现有代码无侵入,理论上只要 vue2 兼容的浏览器都能兼容。

快速开始

安装

$ npm i @zhengxs/composition-api --save

使用

import CompositionAPI from '@zhengxs/composition-api' 

Vue.use(CompositionAPI)

示例

响应式状态

import { defineComponent, reactive, ref } from '@zhengxs/composition-api'

export default defineComponent({
  setup() {
    // 注意和官方的有区别
    const loading = ref(false)

    const state = reactive({
      msg: 'Vue',
    })

    return {
      loading,
      state,
    }
  },
})

生命周期

import {
  defineComponent,
  onBeforeMount,
  onMounted,
  onBeforeDestroy,
  onDestroyed,
} from '@zhengxs/composition-api'

export default defineComponent({
  setup() {
    onBeforeMount(() => {
      // 挂载前,对应 created
    })

    onMounted(() => {
      // 挂载后,对应 mounted
    })

    onBeforeDestroy(() => {
      // 销毁前,对应 beforeDestroy
    })

    onDestroyed(() => {
      // 销毁后,对应 destroyed
    })
  },
})

数据监听

import {
  defineComponent,
  reactive,
  watchEffect,
} from '@zhengxs/composition-api'

export default defineComponent({
  setup() {
    const list = reactive([])

    watchEffect(() => {
      console.log('length:', list.length)
    })

    function addItem() {
      list.push({
        id: Math.random(),
        text: `item ${list.length}`,
      })
    }

    return {
      list,
      addItem,
    }
  },
})

License

  • MIT
回到顶部