v-model 和 Composition API with provide and inject

v-model and Composition API with provide and inject

我想知道如何使用 v-model 和 Composition API.

显示 composition API 的值

目前我有我的 store.js :

import { reactive, toRefs, computed } from "vue";

export default function users() {
    // State
    const state = reactive({
        userForm: null,
    });

    // Mutations
    const UPDATE_USER_FORM = (user) => {
        state.userForm = user;
    };

    // Actions
    const updateUserForm = (payload) => {
        UPDATE_USER_FORM(payload);
    };

    // Getters
    let getUserForm = computed(() => state.userForm);

    return {
        ...toRefs(state),
        updateUserForm,
        getUserForm
    }
}

我在 createApp 中提供我的商店 :

import users from '@/Stores/users';
...
let myApp = createApp({ render: () => h(app, props) });
myApp.provide('userStore', users());

我将我的商店注入到我的组件中:

setup(props, context) {
    const userStore = inject('userStore');

    return { userStore }
}

在模板中我使用了它,但我没有看到值:

我试试这个:

<div>userForm : {{userStore.userForm}}</div> // see the user object

<div>userForm with value : {{userStore.userForm.value.firstname}}</div> // see the firstname value

<div>userForm no value : {{userStore.userForm.firstname}}</div> // don't see the firstname

<input v-model="userStore.userForm.firstname"> // don't see the firstname

我想使用输入中的值...

您应该做的第一件事是将状态放在可组合函数之外,以便所有组件都可以作为一个实例使用:

import { reactive, toRefs, computed } from "vue";
  // State
    const state = reactive({
        userForm: null,
    });
export default function users() {
  

    // Mutations
    ...
    return {
        state,
        updateUserForm,
        getUserForm
    }
}

第二件事是在您想要的任何组件中导入可组合函数,因为 inject/provide 可能有一些反应性问题:

<input v-model="state.userForm.firstname"> 
...

import users from './store/users'
....
setup(props, context) {
    const {state,updateUserForm,getUserForm} = users();

    return { state }
}