我正在尝试使用组合 API 创建一个多步骤表单。在vue 2中我曾经这样做过
email: {
get() {
return this.$store.state.email
},
set(value) {
this.$store.commit("setEmail", value)
}
},
Run Code Online (Sandbox Code Playgroud)
现在我有了自己的商店,我将这个计算属性传递给我的组件stEmail: computed(() => state.email)
。我如何在 get set 中实际使用它?
我正在尝试做类似的事情,但完全不起作用。
let setMail = computed(({
get() {
return stEmail;
},
set(val) {
stEmail.value = val;
}
}))
Run Code Online (Sandbox Code Playgroud)
email: {
get() {
return this.$store.state.email
},
set(value) {
this.$store.commit("setEmail", value)
}
},
Run Code Online (Sandbox Code Playgroud)
或者现在有更好的方法来制作多步骤表单吗?
您可以使用 Composition API 执行相同的操作。useStore
从包中导入vuex
并computed
从vue
:
import { computed } from 'vue';
import { useStore } from 'vuex';
Run Code Online (Sandbox Code Playgroud)
然后在你的setup()
函数中使用它,如下所示:
setup: () => {
const store = useStore();
const email = computed({
get() {
return store.state.email;
},
set(value) {
store.commit("setEmail", value);
}
});
return { email };
}
Run Code Online (Sandbox Code Playgroud)
如果您想避免使用vuex
,您可以使用 定义变量并将ref()
其导出到常规 JavaScript 文件中。这将使您的状态可以在多个文件中重复使用。
状态.js
export const email = ref('initial@value');
Run Code Online (Sandbox Code Playgroud)
Form1.vue/Form2.vue
<template>
<input v-model="email" />
</template>
<script>
import { email } from './state';
export default {
setup() {
return { email };
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
正如格雷戈尔指出的,接受的答案包括一个似乎不起作用的匿名函数,但如果你去掉那部分它就会起作用。<script setup>
这是使用SFC 的示例
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const email = computed({
get() {
return store.state.email
},
set(value) {
store.commit("setEmail", value)
}
})
</script>
<template>
<input type="email" v-model="email" />
</template>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15205 次 |
最近记录: |