繁体   English   中英

为什么 vuex4.0 不能作为 Vue3 onMounted async function 中的钩子工作

[英]Why vuex4.0 not work as hooks inside Vue3 onMounted async function

bar1(), bar2(), bar3() 是三个分离的情况,我想在 foo() 完成时选择其中一个作为真正的bar() ,然后发送到 web 套接字,然后通过 vuex 存储回调值。

1.bar1():我发现如果我把任何bar1()放到onMounted scope中,它不能工作,store turn是未定义的。

2.bar2():我将 XXX.vue 中的参数“store”传递给 bar2(),它可以工作。

3.bar3():奇怪的是,如果 bar3() 不在 onMounted scope 中,它可以工作,尽管这不是异步 function,无需等待 foo(),而不是我期望的方式。

msg_state 在 store.state 中存储一些东西...,我想提交它来更新它的值

问题

  1. bar1(), bar2(), bar3() 有什么区别
  2. 为什么 bar2() as bar() 可以工作,但 bar1() as bar() 不能工作?
  3. 这是因为 bar3() 在 setup() scope 而不是 onMounted() scope 里面?
// In socket.js
// not work
import { useStore } from 'vuex'
export const bar1 = async(input) =>  {
// store is undefined
const store = useStore()
socket = io(url)
    socket.on('message', (msg)  = {
        // commit is not defined
        store.commit("msg_state", msg) 
    })
}

// work
export const bar2 = async(input, store) =>  {
    socket = io(url)
    socket.on('message', (msg)  = {
        store.commit("msg_state", msg) 
    })
}

// work but not async
import { useStore } from 'vuex'
export const bar3 = (input) =>  {
const store = useStore()
    socket = io(url)
    socket.on('message', (msg)  = {
        store.commit("msg_state", msg) 
    })
}

//In XXX.vue
import bar from '@/util/socket.js'
...
export default {
    setup() {
        const xxx = reactive({input: oldVal})
        const store = useStore()
        onMounted(async () => {
        //{input: oldVal}
        await foo()
        //{input: newVal}

        // option1: bar1 as bar
        await bar1(xxx.input) // counldn't work

        // option2: bar2 as bar
        await bar2(xxx.input, store) // this could work

        })
        // option3: bar3 as bar
        bar3(xxx.input) // this could work but not async
    }
}

bar1bar3也是错误的,因为钩子通常应该在setup中调用。 bar2不需要访问整个商店。

使函数async是语义错误,因为它们是异步的但不涉及承诺。 此外,还有message订阅,它不能转换为承诺,除非它是一次性事件。

如果是一次性的,那么在操作之外使用commit意味着特定于商店的业务逻辑分散在应用程序中。 整个bar可能是 Vuex 动作:

const bar = async ({ commit,  state }, input ) =>  {
  // socket is likely a part of state
  await new Promise(resolve => {
    socket.once('message', (msg) => {
      commit("msg_state", msg) 
      resolve(msg);
    });
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM