【问题标题】:How to use Vue Composition API as Global State Across Components?如何使用 Vue Composition API 作为跨组件的全局状态?
【发布时间】:2021-11-10 19:42:26
【问题描述】:

所以我尝试使用 Vue Composition API 作为全局状态。例如,我创建了名为 useLoading.js 的文件作为加载标志。

useLoading.js

import { reactive, toRefs } from '@vue/composition-api'

export default () => {
  const state = reactive({
    isLoading: false
  })

  const setIsLoading = (loading) => {
    state.isLoading = loading
  }

  return {
    ...toRefs(state),
    setIsLoading
  }
}

然后我创建了组件 A,当单击按钮时它将在其中调用 setIsLoading

ComponentA.vue

<template>
  <div @click="showLoading" />
</template>

<script>
import useLoading from '@/composable/useLoading'

export default {
  setup () {
    const { setIsLoading } = useLoading()

    function showLoading () {
      setIsLoading(true)
    }

    return {
      showLoading
    }
  }
}
</script>

我还有组件 B,当 isLoading 的值为 true 时,它将用于渲染 &lt;div&gt;

ComponentB.vue

<template>
  <div v-if="isLoading" />
</template>

<script>
import useLoading from '@/composable/useLoading'

export default {
  setup () {
    const { isLoading } = useLoading()

    return {
      isLoading: isLoading
    }
  }
}
</script>

然而ComponentB.vue 中isLoading 的值没有改变(没有反应)。但是当我打电话给ComponentA.vue时,值确实发生了变化

我觉得在使用 Composition API 作为全局状态时我的实现有问题。有人可以帮忙吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    更新

    刚刚发现我必须从导出函数中排除状态,如果我将它包含在导出函数中,如果在不同的地方调用它会创建其他状态。所以状态不会在组件之间同步。

    import { reactive, toRefs } from '@vue/composition-api'
    
    const state = reactive({
        isLoading: false
    })
    
    export default () => {
    
      const setIsLoading = (loading) => {
        state.isLoading = loading
      }
    
      return {
        ...toRefs(state),
        setIsLoading
      }
    }
    

    【讨论】:

      【解决方案2】:

      这样的事情会起作用:

      useLoading.js

      import { reactive } from 'vue'
      export const state = reactive({
        isLoading: false
      })
      

      App.vue

      <script setup>
      import {state} from './useLoading.js';
      </script>
      
      <template>
        <input v-model="state.isloading" type="checkbox" />
      </template>
      

      【讨论】:

        猜你喜欢
        • 2021-02-09
        • 2022-08-03
        • 1970-01-01
        • 2021-06-24
        • 2021-12-16
        • 2021-02-06
        • 2021-05-12
        • 2022-11-08
        • 2021-01-20
        相关资源
        最近更新 更多