【问题标题】:Update data property / object in vue.js更新 vue.js 中的数据属性/对象
【发布时间】:2016-11-06 19:14:42
【问题描述】:

有没有办法以编程方式更新 vue.js 中的 data 对象/属性?例如,当我的组件加载时,我的数据对象是:

data: function () {
    return {
        cars: true,
    }
}

在触发事件后,我希望data 对象看起来像:

data: function () {
    return {
        cars: true,
        planes: true
    }
}

我试过了:

<script>

module.exports = {

    data: function () {
        return {
            cars: true
        }
    },

    methods: {
        click_me: function () {
            this.set(this.planes, true);
        }
    },

    props: []

}

</script>

但这给了我错误this.set is not a function。有人可以帮忙吗?

提前致谢!

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    Vue 不允许将新的根级反应属性动态添加到已创建的实例中。但是,可以为嵌套对象添加响应式属性,因此您可以创建一个对象并添加一个新属性,如下所示:

    data: function () {
        return {
            someObject:{
                cars: true,
        }
    }
    

    并使用 set 方法添加属性:

    methods: {
            click_me: function () {
                this.$set(this.someObject, 'planes', true)
            }
        }
    

    vue 1.x 使用 Vue.set(this.someObject, 'planes', true)

    reactivity

    【讨论】:

    • 嗨 - 我试过了,但我不断收到vue.common.js?e881:2964 Uncaught TypeError: exp.trim is not a function(…)
    • @user1547174 这看起来像 vue 1.x 试试这个Vue.set(this.someObject, 'planes', true)
    猜你喜欢
    • 2017-12-10
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多