ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Vue3-composition 技巧

2021-05-30 22:29:50  阅读:313  来源: 互联网

标签:vue const 技巧 reactive Vue3 import foo ref 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

标签:vue,const,技巧,reactive,Vue3,import,foo,ref,composition
来源: https://blog.csdn.net/a8725585/article/details/117406694

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有