【问题标题】:vue computed : add new computed value from created lifecycle hookvue computed : 从创建的生命周期钩子中添加新的计算值
【发布时间】:2017-05-04 11:48:54
【问题描述】:

我是 vue 初学者

我正在尝试使用 name 推送计算数据,该名称来自创建实例后的 vuex

如何将新的计算属性推送到 created() 挂钩中的实例??

这里是代码

computed: {
            // 3 - i want to extract the object properties here computed 
            // that is easy bu using spread operator ...
            // Problem : vue intialize computed before the created() hook
            // so the spreed work befor passing the filling the object
            ...this.mapGettersObj
        },

        created(){
            // 1- i can access only this line after creating the object
            this.stocks = this.$store.state
            let arr=[]
            for (let stock in this.stocks){
                arr.push(stock+'Getter')
            }
            // 2 - mapGetters returns an object
            this.mapGettersObj=mapGetters(arr)
        }

如果我可以在创建后创建新的计算值,那将解决问题

【问题讨论】:

  • 请包含您正在处理的代码,并说明您已经尝试过哪些没有用。
  • 我已插入代码

标签: vue.js vue-component


【解决方案1】:

你可以在 beforeCreate 钩子中做到这一点。

beforeCreate: function() {
  this.$options.computed = {
     demo2: function() {
       return this.demo
     }
  }
}

【讨论】:

    【解决方案2】:

    我不知道你为什么要这样做,但如果你想在调用计算之前有一个可用的变量,你可以使用 beforeCreate 钩子:https://alligator.io/vuejs/component-lifecycle/

    你也可以做一些事情

    computed: {
            ...function() {
                this.stocks = this.$store.state
                let arr=[]
                for (let stock in this.stocks){
                    arr.push(stock+'Getter')
                }
                return mapGetters(arr);
            }();
        },
    

    【讨论】:

    • 我认为这是个好主意,但这并不能解决问题,因为 this.$store 仅在创建组件后创建,并且在创建时间之前无效,因此在创建之前调用计算对象时组件它没有看到 this.$store.state
    • 谢谢,我认为这是个好主意,但这并不能解决问题,因为 this.$store 仅在组件创建后创建,并且在创建时间之前无效,因此在调用计算对象之前创建它看不到 this.$store.state 的组件我在创建元素后询问将新的计算数据推送到计算对象,这可能吗?
    • 我有另一个解决方案,但是 beforeCreate() 钩子在创建测试组件之前运行,所以它给出错误,因为:我使用了一个在测试组件内部创建的对象,错误的顺序
    • 感谢 Gerardo Rosciano 我在创建元素后询问将新的计算数据推送到计算对象,这可能吗?
    • 对不起mustafa,我不确定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2018-04-23
    • 2021-03-26
    • 2020-04-06
    • 2019-10-11
    • 2018-11-18
    • 1970-01-01
    相关资源
    最近更新 更多