【问题标题】:Can i reference global variables in a composable function?我可以在可组合函数中引用全局变量吗?
【发布时间】:2022-07-04 21:45:40
【问题描述】:

我正在将项目从 Vue 2 options api 转换为 Vue 3 composition api。 在选项 api 组件中,我有一个名为 componentData 的变量,并且从这个组件中我调用了一个 mixin。当我调用 mixin 时,我可以从 mixin 内部访问所有组件的变量,这是一个示例:

//myMixin.js
export default {
    methods: {
        data_changed() {
            //where componentData is declared in the component
            console.log(this.componentData)
            this.componentData = [1, 2, 3]
        },
    data() {
        return {
            someVar: null
        }
    }
}

我在使用组合 API 时遇到了很多麻烦。而不是 mixins,我有可组合,所以说我有一个组件,我在其中声明一个变量:

import { ref } from 'vue'
import { testData } from '../mixins/useData.js'

export default {
    setup() {
        const componentData = ref([])
        testData()
    }
}

还有我的可组合 useData.js

export function testData() {
    console.log(componentData.value) //undefined
    componentData.value = [1, 2, 3] //will throw error
}

在这种情况下,composable 将返回 undefined。如何在不将它们作为函数参数传递的情况下访问组件的数据?那是因为在 Vue3 中可组合项只应该返回一个值,并且它们的工作方式与 mixins 不同?是否可以从可组合物中更改componentData 的值?

【问题讨论】:

    标签: javascript vue.js vuejs3 vue-composition-api


    【解决方案1】:

    您可以将ref 作为参数传递给testData()

    // useData.js
    export function testData(componentData) {
      componentData.value = [1, 2, 3] ✅
    }
    
    // MyComponent.vue
    import { ref } from 'vue'
    import { testData } from '../mixins/useData.js'
    
    export default {
        setup() {
            const componentData = ref([])
                         ?
            testData(componentData)
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以在文档中引用它!您可以在State Management 下找到参考,这里我引用:

      虽然我们在这里使用单个响应式对象作为存储,但您也可以共享使用其他响应式 API(例如 ref() 或 computed())创建的响应式状态,或者甚至从 Composable 返回全局状态强>:

      他们以这段代码为例:

      import { ref } from 'vue'
      
      // global state, created in module scope
      const globalCount = ref(1)
      
      export function useCount() {
        // local state, created per-component
        const localCount = ref(1)
      
        return {
          globalCount,
          localCount
        }
      }
      

      【讨论】:

        最近更新 更多