javascript - 让组件对状态中的数据变化做出反应
问题描述
我的 vue 应用程序的布局如下:
应用程序.vue
<template>
<div id="app">
<Progress />
<router-view />
<Footer />
</div>
</template>
<script>
import Footer from "@/components/Footer";
import Progress from "@/components/Progress";
export default {
components: {
Footer,
Progress,
},
};
</script>
<template>
<section>
<div class="columns is-mobile pt-6" v-show="progressBar()">
<div class="column is-three-fifths is-offset-one-fifth">
<progress
class="progress is-success"
:value="(progress.count / 9) * 100"
max="100"
>{{ (progress.count / 9) * 100 }} %</progress
>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from "vuex";
export default {
name: "Progress",
methods: {
progressBar() {
console.log(this.progress.status);
if (this.progress.status == false) {
return false;
}
return true;
},
},
computed: mapGetters({
progress: "getProgressBar",
}),
};
</script>
以及进度条的 vuex 存储。
src/store/modules/ProgressBar.js
const state = {
count: 1,
status: false,
};
const getters = {
getProgressBar: state => state,
};
const actions = {
};
const mutations = {
setProgressBar(state, value) {
state.status = value;
},
progressIncrease(state) {
state.status = state.status + 1;
console.log(state.status);
}
};
export default {
state,
getters,
actions,
mutations,
};
/basic
;
<template>
/* code for form layout goes here*/
</template>
<script>
export default {
name: "Basics",
methods: {
toNetworks() {
this.$router.push({ name: "Location" });
this.$store.commit("progressIncrease");
},
/* other codes to handel input */
},
created(){
this.$store.commit("setProgressBar", true);
}
};
</script>
使用上面的代码,我试图count
根据表单步骤增加状态中的变量并根据计算显示进度条。
状态设置正确,我可以通过提交来增加它。但是进度条组件对状态中的更新数据没有反应。
我知道当组件加载到组件中时,该mapGetter
方法只调用一次。<Progress/>
App.vue
是否有任何方法/方式可以对<Progress/>
路由器组件对状态中数据的更改做出反应?
解决方案
在您的 progressIncrease 突变中,您正在增加错误的状态(状态 - 这是一个布尔值)。您将需要两个吸气剂。另外,我认为您的吸气剂应该返回状态和计数状态。你应该有
const mutations = {
progressIncrease(state) {
state.count = state.count + 1;
}
};
const getters = {
count: state => {
return state.count;
},
status: state => {
return state.status;
}
}
在组件中,可以使用 mapGetters 如下
computed: {
...mapGetters([
'count',
'status',
])
}
您可以将“this.status”替换this.progress.status
为“this.progress.count”,将“this.progress.count”替换为“this.count”。如果你愿意,你也可以使用别名。您可以在此处查看有关 getter的更多信息
但是,最好的做法是使用 mapState,因为您要返回状态,而不是像上面链接的 vue 文档示例中那样更改它。
那会变成
computed: mapState({
count: state => state.count,
status: state => state.status,
})
您现在可以将状态称为this.count
和this.status
。同样,如果您愿意,您可以使用别名。您可以在此处了解有关 mapState 的更多信息
推荐阅读
- python - HTML 表单不想发送图像
- python - 将包含字典和字符串值的列表转换为数字数据框列
- swift - 使 Mapbox 注释根据变量具有不同的图像?
- javascript - wp_login_form() 锚点动态重定向
- visual-studio-code - 不能在 C 文件中包含任何内容,vs 代码
- swift - 如何在 SwiftUI 中更改分段选取器的颜色外观?
- pandas - Python pymannkendall 和 Pandas Groupby 解包结果
- corda - Corda - 即使使用通过 QuerybyAccount 查找令牌的相同查询,RedeemFungibleTokens 也会给出“可用状态不足”
- macos - DriverKit 系统扩展可以在启动时匹配热插拔设备吗?
- multidimensional-array - Julia - 使用 mvNormal 生成具有给定均值和协方差矩阵的多元高斯样本