Tencent / wepy

小程序组件化开发框架
https://wepyjs.gitee.io/wepy-docs/
Other
22.49k stars 3.05k forks source link

2.x 关于组件内computed和props的一些bug #2232

Open zhuman90 opened 5 years ago

zhuman90 commented 5 years ago

发现了一个问题,而且挺蛋疼的,就是父组件的某个值如果是通过computed计算得到的,那么把这个值通过props传递给子组件,那么这个值在父组件模板中就没法正常使用了。

就是页面内调用一个父组件(test-father),父组件内部的list属性是通过computed计算得到的,这时候父组件模板中可以直接输出list值,但是,如果在父组件中调用子组件(test-child)的话,这个list值在父组件的模板中就是null。

// index.wpy
// 调用了test-father一个组件

<template>
    <div>
        <test-father :items="items"></test-father>
    </div>
</template>
<script>
import wepy from '@wepy/core';
wepy.page({
       data: {
            items: [{ id: 1, list: [1, 2, 3, 5] }, { id: 2, list: [5, 4, 3, 2, 1] }]
       },
     onLoad() {
        // 如果items是异步数据,子组件内的list值又恢复正常的。
        // setTimeout(() => {
    //  this.items = [{ id: 1, list: [1, 2, 3, 5] }, { id: 2, list: [5, 4, 3, 2, 1] }];
    // }, 1000);
    }
});
</script>
<config>
{
    navigationBarTitleText: 'WePY 2.0 Feature Demo',
    usingComponents: {
      "test-father": "../components/test-father",
    }
}
</config>
// test-father.wpy
// 父组件
<template>
    <div>
        {{list}}
        <!-- 如果注释掉下面的子组件,那么list正常 -->
        <test-child :list="list"></test-child>
    </div>
</template>

<script>

import wepy from '@wepy/core';

wepy.component({
    data: {
        index: 0,
    },
    props: {
        items: {
            type: Array,
            default: null,
        }
    },
    computed: {
        list() {
            if (this.items && this.items.length > 0) {
                return this.items[this.index].list;
             }
              return null;
    }
    },
});
</script>
<config>
{
    usingComponents: {
        "test-child": "./test-child",
    }
}
</config>
// test-child.wpy
// 子组件
<template>
    <div>
        {{ list }}
    </div>
</template>

<script>
import wepy from '@wepy/core';

wepy.component({
    props: {
        list: {
            type: Array,
            default: null,
        },
    },
});
</script>

<config>
{
    usingComponents: {
    }
}
</config>
iniaks commented 5 years ago

2.0.x好像在用computed和props时有很大的问题。

比如用vuex作状态管理的时候,用mapState将store里的一个数组或者对象映射到页面的computed中,它是无法直接传入子组件的props的,这么做会反复触发setData,然后整个小程序卡死爆炸。。。

必须将它手动赋值到页面data里才能使用。

zhuman90 commented 5 years ago

2.0.x好像在用computed和props时有很大的问题。

比如用vuex作状态管理的时候,用mapState将store里的一个数组或者对象映射到页面的computed中,它是无法直接传入子组件的props的,这么做会反复触发setData,然后整个小程序卡死爆炸。。。

必须将它手动赋值到页面data里才能使用。

是的,你说的这个问题我也遇到过,用的wepy/x computed会一直触发,最后我换了其他的状态包。2.0坑还是很多,一点点填吧