开发者在开发某个功能时,经常会遇到某个对象,某个接口在代码多个地方有被使用到,如果每个地方都写一份,一旦其中一个值发生变化了,那么调用的地方都需要修改。而且很容易遗忘某个地方,导致产品存在bug。如何在快应用中定义一个全局对象呢?只需要修改这个全局对象,其他地方都可以同步修改呢?
可在manifest文件的data中定义,然后在各个ux页面通过this.$app.$data.xxx形式去调用。 您也可以在app.ux中定义全局对象,并在各个ux页面通过this.$app.$def.xxx形式去调用。下面我们分别介绍这2个方案的实现。
相关代码如下:
manifest.json文件配置
- "config": {
- "data": {
- "globalData": "GlobalData"
- }
- },
hello.ux 页面
- <template>
- <!-- Only one root node is allowed in template. -->
- <div class="container">
- <input type="button" value="切换" onclick="switchValue" />
- <text>这是一个全局变量{{value}}</text>
- </div>
- </template>
-
- <style>
- .container {
- flex-direction: column;
- justify-content: center;
- align-items: center;
- }
- </style>
-
- <script>
- module.exports = {
- data: {
- componentData: {},
- value: '',
- display: true
- },
- onInit() {
- this.$page.setTitleBar({
- text: 'menu',
- textColor: '#ffffff',
- backgroundColor: '#007DFF',
- backgroundOpacity: 0.5,
- menu: true
- });
- },
- onShow(options) {
- '// Do something when show.'
- this.value = this.$app.$data.globalData
- console.log("message:", this.value);
- },
- switchValue () {
- this.$app.$data.globalData = "test"
- this.value = this.$app.$data.globalData
- console.log("message:", this.value);
- },
- }
- </script>
运行效果:
|
|
|
| 图1 获取全局对象初始值 | 图2 修改全局对象值 |
日志如下:
app.ux代码:
- <script>
- module.exports = {
- onCreate() {
- console.info('Application onCreate');
- },
- onDestroy() {
- console.info('Application onDestroy');
- },
- dataApp: {
- globalData: "GlobalData in app.ux"
- }
- }
- </script>
hello.ux代码:
- <template>
- <!-- Only one root node is allowed in template. -->
- <div class="container">
- <input type="button" value="切换" onclick="switchValue" />
- <text>这是一个全局变量{{value}}</text>
- </div>
- </template>
-
- <style>
- .container {
- flex-direction: column;
- justify-content: center;
- align-items: center;
- }
- </style>
-
- <script>
- module.exports = {
- data: {
- componentData: {},
- value: '',
- display: true
- },
- onInit() {
- this.$page.setTitleBar({
- text: 'menu',
- textColor: '#ffffff',
- backgroundColor: '#007DFF',
- backgroundOpacity: 0.5,
- menu: true
- });
- },
- onShow(options) {
- '// Do something when show.'
- this.value = this.$app.$def.dataApp.globalData
- console.log("message:", this.value);
- },
- switchValue() {
- this.$app.$def.dataApp.globalData = "test"
- this.value = this.$app.$def.dataApp.globalData
- console.log("message1111111:", this.value);
- },
- }
- </script>
运行效果:
|
|
|
| 图1 获取全局对象初始值 | 图2 修改全局对象值 |
日志如下:
欲了解更多详情,请参阅:
快应用manifest.json文件:
https://developer.huawei.com/consumer/cn/doc/development/quickApp-References/quickapp-manifest
快应用script脚本:
https://developer.huawei.com/consumer/cn/doc/development/quickApp-References/quickapp-script#h2-1575380435413