zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【快应用】$set数据方法使用案例

2023-09-11 14:17:16 时间

问题背景:

快应用中使用$set数据方法来动态设置数据,数据设置不生效,页面显示的是undefined而不是设置的数据,该如何解决?

 

相关代码:

<template>

  <!-- Only one root node is allowed in template. -->

  <div class="container">

    <text class="title" id="txt">{{value}}</text>

  </div>

</template>

<style>

  .container {

    flex-direction: column;

    justify-content: center;

    align-items: center;

  }

  .title {

    font-size: 60px;

    align-self: center;

  }

</style>

<script>

  module.exports = {

    data: {

      componentData: {},

    },

    onShow(options) {

      '// Do something .'

      this.$set('value', "Hello ")

      this.$vm('txt').$set('value', "Hello ")

    },

  }

</script>

截图:

cke_1436.png

 

问题分析及解决方案:

这是因为问题中的$set方法在onshow生命周期里设置,而在data数据里没有定义相应变量导致的。在快应用中$set方法添加数据属性,使用有两种方式:一个是写在oninit里,一个是在onshow里设置同时要在data属性里定义变量。否则在<template>中数据绑定无法生效。

方法一:

<script>

  module.exports = {

    data: {

      componentData: {},

    },

    onInit() {

      '// Do something .'

      this.$set('value', "Hello ")

      this.$vm('txt').$set('value', "Hello ")

    },

  }

</script>

方法二:

<script>

  module.exports = {

    data: {

      componentData: {},

      value: ''

    },

    onShow() {

      '// Do something .'

      this.$set('value', "Hello ")

      this.$vm('txt').$set('value', "Hello ")

    },

  }

</script>

截图:

cke_5841.png

​欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh