【发布时间】:2021-08-25 01:43:03
【问题描述】:
我正在使用组合 API 进行状态管理,但它不是反应式的。
这是我的商店文件:
import { readonly, reactive } from "@vue/reactivity";
const state = reactive({
lang: "en",
page: 1,
words: [
{
word: "Hello",
repeat: 92,
sentences: [],
},
{ word: "Love", repeat: 128 },
{ word: "Good", repeat: 50 },
{ word: "New", repeat: 12 },
{ word: "Hello", repeat: 12 },
{ word: "Love", repeat: 12 },
{ word: "Good", repeat: 12 },
{ word: "New", repeat: 12 },
{ word: "Hello", repeat: 12 },
{ word: "Love", repeat: 12 },
{ word: "Good", repeat: 12 },
{ word: "New", repeat: 12 },
{ word: "Hello", repeat: 12 },
{ word: "Love", repeat: 12 },
{ word: "Good", repeat: 12 },
{ word: "New", repeat: 12 },
],
});
const methods = {
changePage(i: number): void {
state.page = i;
},
emptyTheList() {
state.words = [];
},
};
export default { state, methods };
这是一个使用注入存储的组件:
<template>
<div class="btn-group bg-gray-50 mt-6 pt-6 pb-6 flex justify-center">
<button class="btn" :id="wordsInfo.state.page"><<</button>
<button
class="btn"
v-for="i in numberOfPages"
v-bind:key="i"
:class="page === i && 'btn-active'"
@click="changePage(i)"
>
{{ i }}
</button>
<button class="btn">>></button>
</div>
</template>
<script>
import { ref, computed, inject } from "vue";
export default {
name: "WordCardsPagination",
props: {
func: Function,
},
setup(props, context) {
console.log(props.func);
const wordsInfo = inject("wordsInfo");
const numberOfPages = computed(() => {
return Math.ceil(wordsInfo.state.words.length / 12);
});
const page = ref(wordsInfo.state.page);
const changePage = (i) => {
wordsInfo.methods.changePage(i);
page.value = wordsInfo.state.page;
};
return {
numberOfPages,
wordsInfo,
page,
changePage,
};
},
};
</script>
上面的代码运行没有问题,但是如果使用wordsInfo.state.page而不是wordsInfo.state.page,则页面引用被删除:
<button
class="btn"
v-for="i in numberOfPages"
v-bind:key="i"
:class="wordsInfo.state.page === i && 'btn-active'"
@click="wordsInfo.methods.changePage(i)"
>
{{ i }}
</button>
组件不再是响应式的,即使 console.log 显示值已更改
【问题讨论】:
-
您正在商店中导入
reactive,但实际上并没有在任何地方使用它。这是故意的吗? -
@MichalLevý 我确实使用了它,但没有任何区别,当我尝试不同的解决方案时将其删除。
-
为什么要从
ref中创建ref?由于响应式遍历对象,直到它具有标量值并将ref放在它的位置。所以wordsInfo.state.page已经是ref,你再把它贴在ref中。或者,也许我现在弄错了什么。我可能在想toRefs。 -
应该的。我看不出有什么问题。除了代码是尝试解决方案的奇怪组合。也许你应该清理它并创建可运行的Minimal, Reproducible Example ...例如在 Codesandbox/Codepen
-
这是一个长镜头,可能不是问题,但以防万一......尝试始终从“vue”而不是“@vue/reactivity”导入(就像在你的商店中一样)跨度>
标签: javascript vuejs3 state-management