Share State Between Two Pages
Change the notification setting on a second page and show the updated value when the user returns home.
Declare Shared State in App
Add globalData to the object exported from app.js in an existing AIUI project. Both pages can access the notification setting through getApp().
export default {
globalData: {
notificationsEnabled: false
}
};
Register the Settings Page
Keep the home page in the pages array in app.json and add the settings page.
{
"pages": ["pages/index/index", "pages/settings/index"]
}
Write Shared State on the Settings Page
Create pages/settings/index.ink. When the user taps the button, write the new value to globalData and return to the home page.
<script setup>
export default {
enableNotifications() {
getApp().globalData.notificationsEnabled = true;
wx.navigateBack();
}
};
</script>
<page>
<button bindtap="enableNotifications">Enable notifications and go back</button>
</page>
Read the State When the Home Page Reappears
Save this example as pages/index/index.ink. Each time the home page appears, onShow() copies the shared value to the page’s data so the template can display it.
<script setup>
export default {
data: { notificationsEnabled: false },
onShow() {
this.setData({
notificationsEnabled: getApp().globalData.notificationsEnabled
});
},
openSettings() {
wx.navigateTo({ url: '/pages/settings/index' });
}
};
</script>
<page>
<view>
<text>{{ notificationsEnabled ? 'Notifications on' : 'Notifications off' }}</text>
<button bindtap="openSettings">Open Settings</button>
</view>
</page>
Verify the Result
Open the home page and check that it shows “Notifications off.” Open Settings, then tap “Enable notifications and go back.” The home page should show “Notifications on.” The shared value lasts for the lifetime of the current App instance.
See App for the application instance.