Search code examples
vue.jscomponentsweex

weex data change to update to child component


<template>
    <topView viewInfo="cardInfo"></topView>
    <bottomView viewInfo="cardInfo"></bottomView>
<template>
<script>
     module.exports = {
        data: {
          viewInfo:{
             attr0:value0,
             attr1:value1
          }
       },
       mounted:function(){
          getDataFromServer();
       },
       methods:{
          getDataFromServer:function(){
            var me = this;
            var httpRequest = Service.getViewInfo();
            httpRequest.on("success",function(data){
               me.viewInfo.attr2 = data.info.attr2;
               me.viewInfo.attr3 = data.info.attr3;
               me.viewInfo.attr4 = data.info.attr4;

           });
           httpRequest.send();
      }
    }
  }
</script>

topView.vue

<template>
<div>
  <text>{viewInfo.attr0}</text>
  <div v-for="(item, index) in getItems">
        <text>{item.text}</text>
        <text>{item.info}</text>
  </div>
  <text>{viewInfo.attr1}</text>
</div>
<template>

<script>
 module.exports = {
    data: {
      itemInfo:[
          {text:'text 0',info:"****"},
          {text:'text 1',info:"****"},
          {text:'text 2',info:"****"}
      ]
    },
    props:{
        viewInfo:{}
    },
    computed:{
      getItems:function(){
        this.itemInfo[0].info = this.viewInfo.attr2 +" point";
        this.itemInfo[1].info = this.viewInfo.attr3 +" point";
        this.itemInfo[2].info = this.viewInfo.attr4 +" point";

        return itemInfo;
      }
    },
    methods:{

       }
    }
</script>

when i get data from server,and add some attr value to viewInfo. the child comphonent can update direct value.the compute values can't update relation to props data from parent component.

need some help.how can i update compute items value when i update parent component "viewInfo" values.


Solution

  • Vue cannot detect the changes when you directly set an item with the index, i.e. this.itemInfo[0].info = this.viewInfo.attr2 +" point" Is not reactive.

    Use Vue.set instead, for the above:

    // create a new item
    var newItem = Object.assign({}, this.itemInfo[0], { info: this.viewInfo.attr2 +" point" })
    // set the new item to the specific index
    this.$set(this.itemInfo, 0, newItem)
    

    You can read more about List Rendering Caveats here: