0

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

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

4

2 回答 2

1

我已经解决了!

辅助功能:

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]
    }
于 2021-06-30T13:41:10.393 回答
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" />
于 2021-06-30T09:55:54.887 回答