需求:侧边栏显示报警信息数量
在store/project.js文件中定义相关状态
// 存储项目信息
const projectInfo = JSON.parse(sessionStorage.getItem('projectInfo')) ? JSON.parse(sessionStorage.getItem('projectInfo')) : '';
import { getUntreatedProjectAlarm } from '@/api/managealarm'
const state = {projectInfo: projectInfo,// 菜单按钮是否展开launch: true,// 报警信息数量alarmNumber: 0
}const mutations = {SET_PROJECT_INFO: (state, projectInfo) => {state.projectInfo = projectInfosessionStorage.setItem('projectInfo', JSON.stringify(projectInfo))},SET_LAUNCH: (state) => {state.launch = !state.launch},SET_ALARMNUMBER: (state, alarmNumber) => {state.alarmNumber = alarmNumber},
}const actions = {setProject({commit}, projectInfo) {commit('SET_PROJECT_INFO', projectInfo)},getAlarmNumber({ commit }) {return new Promise(() => {let params = {page: 1,rows: 500,alarmType: '',startDate: '',endDate: '',everconfirmed: '',projectId: state.projectInfo.id}getUntreatedProjectAlarm(params).then((res) => {let alarmNumber = res.total;commit('SET_ALARMNUMBER', alarmNumber)})})}
}export default {namespaced: true,state,mutations,actions
}
在侧边栏Sidebar.vue页面中调用
<el-badge :value="alarmNumber" class="item custombge">{{ subItem.name }}
</el-badge>
computed: {//使用计算属性,如果其他页面更改了状态(数量)那么它也更这变化alarmNumber() {return this.$store.state.project.alarmNumber;}},
mounted() {// 页面加载后调用store里面的action方法获取数据this.$store.dispatch("project/getAlarmNumber");
},
在报警信息alarm.vue页面中
<el-table-column label="操作" align="center"><template slot-scope="scope"><div><el-button v-if="scope.row.everconfirmed == 0" type="primary" size="mini" @click="isTrue(scope.row.id)">确认</el-button><el-button v-else type="info" size="mini" @click="isTrue(scope.row.id)">取消</el-button></div></template>
</el-table-column>
methods: {// 点击确认、取消按钮调用此方法isTrue(val) {let params = {ids: [val]}batchUpdateProjectAlarmState(params).then((res) => {//获取页面数据// this.search();//重新更新报警信息数量this.getAlarmNumber();})},getAlarmNumber() {this.$store.dispatch("project/getAlarmNumber");},}
提示
javascript 一般调用mutations中的方法是使用commit 例如 this.$store.commit("project/SET_LAUNCH") 一般调用actions 中的方法是使用dispatch 例如 this.$store.dispatch("project/getAlarmNumber");
结果截图:
点击一个确认后