首页 > 解决方案 > Vue 3 组合 API 计算函数

问题描述

试图将我的代码切换到 Vue 3 附带的新组合 API,但我无法让它工作。

export default {
    props: {
       classProp: {type: String},
       error: {type: String},            
    },
    setup(){
     
        // move to here (this is not working)
        computed(() => {
          const classObject = () => {
            return ['form__control', this.classProp, 
                {              
                    'form__invalid': this.error
                }
            ]
          }
        })
    },
    computed: {
         classObject: function () {
             return ['form__control', this.classProp, 
                 {              
                     'form__invalid': this.error
                 }
             ]
         }
    },
}

标签: vuejs3

解决方案


一起跳过“计算”,您需要使用“ref”或“reactive”。这些是模块:

<script>
    import { ref } from 'vue'
    setup(){
     const whateverObject = ref({ prop: "whatever initial value" });
     whateverObject.value.prop= "if you change something within setup you need to access it trough .value";
     return { whateverObject } // expose it to the template by returning it
    }
</script>

如果你想使用类,你可以像我自己的这个例子一样导入它们:

import { APIBroker } from '~/helpers/APIbroker'
const api = new APIBroker({})

现在“api”可以在 setup() 或任何地方使用


推荐阅读