【问题标题】:Vue 3 with Vuex 4Vue 3 和 Vuex 4
【发布时间】:2021-09-12 11:07:37
【问题描述】:

我将 Vue 3 与组合 API 一起使用,并试图了解如何直接从 Vuex 映射我的状态,以便模板可以使用它并使用 v-model 即时更新它。

mapState 是否可以解决此问题?不,我需要通过 getter 获取我的状态,在模板中打印出来,然后为我的状态中的每个字段手动提交......在 Vue 2 和 Vuex 中,我有这个 100% 动态

【问题讨论】:

  • 请分享代码

标签: vue.js vuex vuejs3 vuex4


【解决方案1】:

要在您的输入和存储 state 之间进行双向绑定,您可以使用 set/get 方法使用可写计算属性:

setup(){
  const store=useStore()

   const username=computed({
       get:()=>store.getters.getUsername,
       set:(newVal)=>store.dispatch('changeUsername',newVal)
    })

return {username}
}

模板:

<input v-model="username" />

【讨论】:

  • 我明白你的意思,这是唯一的方法吗?假设您有 10-15 个字段,那么您需要为每个字段计算一个,我希望 Vuex 能够为您自动映射它
  • @nahoj Afaik 这是为 Vuex 5 计划的。目前您可以使用适合您需求的自己的辅助函数来解决
  • 我明白了。你有这样的辅助函数的例子吗?
  • @BoussadjraBrahim 这是一个普遍的问题,而不是特定于代码的问题。我知道你可以使用、getter 和 setter。我一直在寻找动态地图功能。
  • 如果你能举个有用的例子
【解决方案2】:

我已经解决了!

辅助函数:

import { useStore } from 'vuex'
import { computed } from 'vue'

const useMapFields = (namespace, options) => {
const store = useStore()    
const object = {}

if (!namespace) {
    console.error('Please pass the namespace for your store.')
}

for (let x = 0; x < options.fields.length; x++) {
    const field = [options.fields[x]]
    
    object[field] = computed({
        get() {
            return store.state[namespace][options.base][field]
        },
        set(value) {
            store.commit(options.mutation, { [field]: value })
        }
    })
}


return object
}

export default useMapFields

在 setup() 中

       const {FIELD1, FIELD2}  = useMapFields('MODULE_NAME', {
            fields: [
                'FIELD1',
                 etc…
            ],
            base: 'form', // Deep as next level state.form
            mutation: 'ModuleName/YOUR_COMMIT'
        })

Vuex 突变:

    MUTATION(state, obj) {
        const key = Object.keys(obj)[0]
        state.form[key] = obj[key]
    }

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2022-01-16
    • 2021-11-04
    • 2021-07-25
    • 2021-06-22
    • 1970-01-01
    • 2019-10-15
    • 2021-11-28
    • 2021-05-18
    相关资源
    最近更新 更多