首页 > 解决方案 > 直接导出反应属性与 toRef 包装

问题描述

我正在使用新的组合 API ( https://github.com/vuejs/composition-api ) 创建我的 Vue 2“商店”。我想公开我的状态的一个子集。

参考源属性保持反应性的正确方法是什么?

const state = reactive({
  somethingInternal: '',
  name: ''
})

// is this enough?
export const name = state.name
// or do I need to do this?
export const name = toRef(state, 'name')

标签: javascriptvue.jsvuejs3vue-composition-apivue-reactivity

解决方案


你必须使用toRef来保持反应性。

这仅导出字符串文字:

export const name = state.name

但这保留了与反应属性的连接:

export const name = toRef(state, 'name')

如果您将所有的导入state和导出name都导入另一个模块,然后更改state.name,则更改将反映在toRef导出中,而不是文字中。


推荐阅读