vue 计算:从创建的生命周期钩子添加新的计算值

Mus*_*mey 5 vue.js vue-component

我是 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)
        }
Run Code Online (Sandbox Code Playgroud)

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

小智 6

您可以在 beforeCreate hook\xe3\x80\x82 中执行此操作

\n\n
beforeCreate: function() {\n  this.$options.computed = {\n     demo2: function() {\n       return this.demo\n     }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n


小智 0

我不知道你为什么要做你所做的事情,但是如果你想在调用计算之前有一个可用的变量,你可以使用 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);
        }();
    },
Run Code Online (Sandbox Code Playgroud)