Vue3-composition 技巧

Ref自动解包

  • watch直接接受Ref作为监听对象,在回调中解包
const counter = ref(0)

watch(counter, count => {
 console.log(count) // same as `counter.value`
})
  • 在模板中自动解包

  • reactive解包

import { ref, reactive } from 'vue'
const foo = ref('bar')
const data = reactive({ foo, id: 10 })
data.foo // 'bar'
  • unref() 获取ref值,不为ref时直接返回

重复使用已有Ref

将已有ref 传递给’ref()'函数,会返回原有ref

const foo = ref(1)   // Ref<1>
const bar = ref(foo) // Ref<1>
foo === bar // true


/**********************************/
function useFoo(foo: Ref<string> | string) {
  // 不需要额外操作
  const bar = isRef(foo) ? foo : ref(foo)

  // 与上面的代码等效
  const bar = ref(foo)

  /* ... */
}

Ref组成的对象优点

  • 可直接结构Ref 使用
  • 想自动解包时可使用reactive转换为对象
import { ref, reactive } from 'vue'

function useMouse() {
  return { 
    x: ref(0),
    y: ref(0)
  }
}

const { x, y } = useMouse() // 解构
const mouse = reactive(useMouse()) // 转换为对象

mouse.x === x.value // true

类型安全的Provide/Inject

使用Vue提供的InjectionKey<T> 类型工具在不同上下文中共享类型

// context.ts
import {InjectionKey} from 'vue'

export interface UserInfo{
  id: number
  name: string
}
export const injectKeyUser:InjectionKey<UserInfo> = Symbol()
// parent.vue
import {provide} from 'vue'
import {injectKeyUser} from './context'

export default {
  setup(){
    provide(injectKeyUser,{
      id:'7', // 类型错误
      name:'aan'
    })
  }
}

// child.vue
import {inject} from 'vue'
import {injectKeyUser} from './context'
export default {
  setup(){
    const user = inject(injectKeyUser)
    if(user){
      console.log(user.name) // aan
    }
  }
}

状态共享(vuex) vue3中天然支持

  • 组合式api,不支持ssr
//share.ts
import {reactive} from 'vue'
export const state = reactive({
  foo:1,
  bar:'bar'
})
// A.vue
import {state} from './share.ts'
state.foo=2

// B.vue
import {state} from './share.ts'
console.log(state.foo) // 2
  • 兼容ssr共享
    使用provideinject共享状态
export const myStateKey: InjectionKey<MyState>=Symbol()
export function creatMyState(){
  const state={
    //...
  }
  return {
    install(app:App){
      app.provide(myStateKey,state) // 注入
    }
  }
}

export function useMyState():MyState{
  return inject(myStateKey)
}
// main.ts
// 全局注入
const app = createApp(App)
app.use(createMyState())

// A.vue
// 任何组件中使用获得状态对象
const state = useMySate()

相关文档
可组合的 Vue - VueConf China 2021

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值