可组合项中的 Ref 当放置在返回函数内部时不是反应性的,而当放置在返回函数外部时可以工作

Vic*_*tor 6 vue.js vue-composition-api

我使用带有插件的Vue 2@vue/composition-api

我做了一个简单的可组合项:

import { ref } from '@vue/composition-api'

export function useRfp() {
  const files = ref([])

  return {
    files
  }
}
Run Code Online (Sandbox Code Playgroud)

我更新了使用此可组合项的组件中的文件数组,如下所示:files.value = ...

但是,它仅在可组合项如下所示时才有效:

import { ref } from '@vue/composition-api'

const files = ref([]) // <-- Notice the const is outside the useRfp function

export function useRfp() {
  return {
    files
  }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生这种情况,因为在 VueJS 文档中,他们有一个鼠标跟踪器的示例,该示例在函数内使用 refs:

// mouse.js
import { ref, onMounted, onUnmounted } from 'vue'

// by convention, composable function names start with "use"
export function useMouse() {
  // state encapsulated and managed by the composable
  const x = ref(0)
  const y = ref(0)

  // a composable can update its managed state over time.
  function update(event) {
    x.value = event.pageX
    y.value = event.pageY
  }

  // a composable can also hook into its owner component's
  // lifecycle to setup and teardown side effects.
  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))

  // expose managed state as return value
  return { x, y }
}
Run Code Online (Sandbox Code Playgroud)

这是有道理的,因为它封装在函数内。

我所说的“不起作用”是指当我更新一个组件中的值时,另一个组件中的值仍然为空。它是数组还是字符串并不重要。

为什么会发生这种情况?我觉得我不应该将引用放在函数之外。

小智 1

我过去也遇到过这个问题,我需要使用可组合项中的数据构建可重用的警报组件。
据我所知,ref/reactive函数内的值将始终以这些值开头,因为它们在函数中具有默认值。
但是,如果将这些值放在外部,这些值将持续存在,就像基本状态或存储一样。
当您稍后需要在其他地方访问这些值时,每次调用可组合项时它们都不会重置。

事实上,带有鼠标坐标的 vue 示例将始终从 at 开始,{0,0}因为当您调用该可组合项时它们会重新初始化。