考虑以下使用Vue 3中的组合API的简单示例。我想在组件的函数中使用test的实例。
<script>
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
name: 'Test',
setup(){
let test = ref()
onMounted(() => {
doSomething()
})
return{
test,
doSomething
}
}
})
function doSomething(){
console.log(test) //<-- undefined
console.log(this.test) //<-- undefined
}
</script>
如何在doSomething()内部访问test?我的理解是setup()返回的任何内容应该在整个组件中都可用,就像选项API中的data()属性一样。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你必须将
ref作为参数传递<script> import { defineComponent, ref, onMounted } from 'vue' export default defineComponent({ name: 'Test', setup () { let test = ref(null) onMounted(() => { doSomething(test.value) }) return { test, doSomething } } }) function doSomething (param) { console.log(param); // null } </script>另一种方法:
// functions.js import { ref } from 'vue' export let test = ref(null)// vue-file <script> import { defineComponent, ref, onMounted } from 'vue' import { test } from '../utils/functions.js' export default defineComponent({ name: 'Test', setup () { onMounted(() => { doSomething(test) }) return { test, doSomething } } }) function doSomething (param) { console.log(test.value); // <-- instant access console.log(param.value); // <-- import via parameter } </script>