Vue中为什么属性不能实时绑定?

这是一个很低级的错误,但是如果不小心就会犯二。

在Vue中要进行数据绑定,首先要声明这个属性,然后vue才会监听这些属性的数据变化。但是,如果一个object,即使你不设置某些属性,在你访问时也并不会报什么错误,但是Vue却不能对这些属性进行数据监听。例如下面的例子。

<template>
    <div>
        <template v-for="(item, index) in items">
            <button @click="changeActive(index)">{{item.title}}</button>
            <ul :class="{'active': item.active}">
                <li v-for="o in item.data">{{o}}</li>
            </ul>
        </template>
    </div>
</template>

<script>

    export default {
        data () {
            return {
                items: [{
                    active: true,
                    title: '动物',
                    data: ['cat', 'fish', 'mouse']
                }, {
                    title: '人',
                    data: ['girl', 'body']
                }, {
                    title: '物体',
                    data: ['cup', 'computer', 'keyboard']
                }]
            }
        },
        methods: {
            changeActive (index) {
                this.items[index].active = true
                console.log(this.items)
            }
        },
    }
</script>

<style lang="less">
    ul {
        display: none;
        &.active {
            display: block;
        }
    }
</style>

这里点击按钮时并不能立即将active设置为true的内容显示出来,这是因为事先并没有在items数组中为每一项都设置active,所以这些属性并没有被vue接管。

那么,将上述的changeActive代码稍加修改,就可以避免这种问题。

changeActive (index) {
    //保证属性被初始化
    const items = this.items.map(item => {
        item.active = false
        return item
    })
    items[index].active = true
    this.items = items
}

所以在使用vue进行数据操作时,一定要将用到的属性事先初始化好,以免引起不必要的问题。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注