Vuex状态跨页更新不生效问题排查:勾选SSO复选框后Lnb组件无法隐藏Account菜单
Let's break down the problems in your code and fix them step by step:
1. Wrong Vuex Dispatch Path
In login.vue, you're dispatching the action with this.$store.dispatch('store/setPageSso', this.sso)—but your store is the root module (not a namespaced sub-module), so you don't need the store/ prefix. This means your action wasn't actually firing, so the pageSso state never updated from its initial value of 0.
Fix it by removing the prefix:
submit() { this.$store.dispatch('setPageSso', this.sso) }
If you intended to use a namespaced module, you'd need to add export const namespaced = true to your store/store.js, but based on your current setup, the root module approach is correct.
2. Type Mismatch Between Checkbox Value and State
Your checkbox uses true-value="1" and false-value="0"—these are string values, but your pageSso state is initialized as a number (0). When you save the string "1" to state, the check pageSso != 1 will evaluate to true (because "1" !== 1), so the Account menu won't hide.
You have two easy fixes here:
Option A: Bind checkbox values as numbers
Add colons to bind the values as numbers instead of strings:
<input class="checkbox_sso" type="checkbox" v-model="sso" :true-value="1" :false-value="0" >SSO checkbox
Also set the initial sso value to a number in login.vue:
data() { return { sso: 0 } }
Option B: Convert the value to a number in the mutation
If you prefer to keep the checkbox values as strings, convert the incoming data to a number in your mutation:
export const mutations = { setPageSso(state, data) { console.log('mutations setPageSso data', data) state.pageSso = Number(data) // Convert to number } }
3. Verify State in Lnb Component
The mounted hook in Lnb.vue only runs once when the component loads. After fixing the first two issues, when you log in and navigate to the dashboard, the component will initialize with the updated pageSso state, and your console.log should show the correct value (1 when SSO is checked).
You can also simplify the mapState call since you're using the root module:
computed: { ...mapState({ pageSso: (state) => state.pageSso, }), }
Final Result
Once you apply these fixes, checking the SSO checkbox and clicking login will update the pageSso state to 1, and the Account menu in Lnb.vue will be hidden as expected.
内容的提问来源于stack exchange,提问作者niddddddfier

