vue3 composition-api

521 阅读1分钟

vue3一些API使用总结:

$refs:

<template>
	<div ref="root" @click="handleClick"</div>
</template>

setup(props, ctx){
	//$refs
	const root = ref(null)
	const handleClick = () => {
		console.log(root)
	}
	return {
		root
	}
}

声明周期

beforeCreate(删除) -> 使用 setup()
created(删除) -> 使用 setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
errorCaptured -> onErrorCaptured
// 新增的钩子函数
onRenderTracked
onRenderTriggered

provide 和 inject

import { provide, inject } from 'vue'
const ThemeSymbol = Symbol()
const Ancestor = {
  setup() {
    provide(ThemeSymbol, 'dark')
  },
}
const Descendent = {
  setup() {
    const theme = inject(ThemeSymbol, 'light' /* optional default value */)
    return {
      theme,
    }
  },
}
// 注入的响应性 可以使用 ref 来保证 provided 和 injected 之间值的响应
// 提供者:
const themeRef = ref('dark')
provide(ThemeSymbol, themeRef)

// 使用者:
const theme = inject(ThemeSymbol, ref('light'))
watchEffect(() => {
  console.log(`theme set to: ${theme.value}`)
})

vuex,vue-router,ElementUI 的一些 $方法可以从 root 中取得

export default {
  setup(props, ctx) {
    const { $store, $router, $route, $message, $confirm } = ctx.root
  }
}

getters

// 1
export default {
  setup(props, ctx) {
    const { $store } = ctx.root
    // 此处先省略 data 部分...
    const permissions = computed(() => $store.getters.permissions)
    const canUpdate = () => permissions.includes('update')
    const canDelete = () => permissions.includes('delete')
    return {
      canUpdate,
      canDelete
    }
  }
}
// 2
import { computed }  from 'vue'
import { useStore } from 'vuex'
const module = 'myModule'
export default {
    setup() {
        const store = useStore()
        return {
            // getter
            one: computed(() => store.getters[`${module}/myStateVariable`],
            // state
            two: computed(() => store.state[module].myStateVariable,
        }
    }
}

$store

setup(props, ctx){
	// $store
	const {$store} = ctx.root
	console.log($store)
	// computed
	
}

message,message, router, confirm,confirm, store

import { computed, onCreated } from 'vue-function-api'

export default {
  setup(props, ctx) {
  	// <--- setup() 中不可以使用 this 访问当前组件实例, 可以通过 setup 的第二个参数 context 来访问 vue2.x API 中实例上的属性。
    const { $message, $router, $confirm, $store } = ctx.root 
    // 此处先省略 data 部分...

    // method
    const fetchCity = async () => {
      const response = await fetchCityApi()
      citys.value = response.data // <--- 划重点,通过 value() wrap初始化的变量在 setup 内部引用值或者修改值都要加 .value
    }
    const fetchList = async () => {
      const response = await fetchListApi(query.value)
      list.value = response.data
    }
    const delete = async id => {
      const response = await deleteItem(id)
      const { status, msg } = response.data
      if (status !== 'ok') return $message.error(msg)
      $message({
        type: 'success',
        message: '删除成功'
      })
    }
    confirm(id) {
      $confirm(`确认删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delete(id)
      }).catch(() => {
        $message({
          type: 'info',
          message: '已取消'
        })
      })
    }
    detail(id) {
      $router.push({
        path: '/detail',
        query: { id }
      })
    }
    // lifecycle
    onCreated(() => {
      fetchCity()
      fetchList()
    })
    return {
      fetchCity,
      fetchList,
      confirm,
      detail // <--- 这里只导出 template 的依赖
    }
  }
}

watch

import { watch } from 'vue-function-api'

export default {
  setup() {
    // ...
    watch(
      query,
      val => {
        fetchList()
      },
      { deep: true }
    )
    // 或者
    watch(
      () => query.value,
      val => {
        fetchList()
      },
      { deep: true }
    )

    // ...
  }
}

vuex,vue-router,ElementUI 的一些 $方法可以从 root 中取得

export default {
  setup(props, ctx) {
    const { $store, $router, $route, $message, $confirm } = ctx.root
  }
}

vuex4

import { createApp } from 'vue'
import { createStore } from 'vuex'
// Create a new store instance.
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
const app = createApp({ /* your root component */ })
// Install the store instance as a plugin
app.use(store)

//
import { useStore, mapState, mapGetters} from 'vuex'
export default {
  // ...
  step(){
  	const store = useStore()
    store.commit('increment')
    console.log(store.state.count) // -> 1
    
    store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
  },
  computed: mapState({
    // arrow functions can make the code very succinct!
    count: state => state.count,

    // passing the string value 'count' is same as `state => state.count`
    countAlias: 'count',

    // to access local state with `this`, a normal function must be used
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
  //
  computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}