我想从“”部分中的组件导出函数并在另一个组件中使用它。
我尝试过这样的:
<!-- TestHeading.vue -->
<template>
<h1>{{ title }}</h1>
</template>
<script setup>
import { ref } from 'vue';
const title = ref('title');
export function set_title(new_title) {
title.value = new_title;
}
</script>
<!-- TestDocument.vue -->
<template>
<TestHeading />
<p>Main text</p>
</template>
<script setup>
import { TestHeading, set_title } from '../components/TestHeading.vue';
set_title('new title');
</script>
这只是给了我错误:
<script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.
省略“导出”我刚刚得到:
Uncaught SyntaxError: import not found: set_title
在 TestDocument.vue 中。
有办法吗? 组件(TestHeading)在整个文档中只会出现一次,所以我应该能够使用像这样的全局函数来设置标题。
推荐的方法是使用
defineExpose
宏公开函数,然后在子组件上使用模板引用 :
<!-- TestHeading.vue -->
<template>
<h1>{{ title }}</h1>
</template>
<script setup>
import { ref } from 'vue';
const title = ref('title');
function set_title(new_title) {
title.value = new_title;
}
defineExpose({
set_title
})
</script>
<!-- TestDocument.vue -->
<template>
<TestHeading ref="heading" />
<p>Main text</p>
</template>
<script setup>
import { TestHeading, set_title } from '../components/TestHeading.vue';
const heading = ref()
heading.value.set_title('new title');
</script>