Vue 3 通过 this. 调用 setup 暴露的函数
<script src="https://cdn.uv.cc/vue/3.5.13/vue.global.prod.js"></script>
<div id="app">
<div>
<p>Count: {{ count }}</p>
<p>Doubled Count: {{ doubledCount }}</p>
<button @click="increment">Increment</button>
<button @click="proxit">我是 methods 中的函数,我会调用 setup 暴露的函数</button>
</div>
</div>
<button onclick="ex()">
我是 Vue 外部的 js 函数,我调用了 Vue app 中 setup 暴露的函数
</button>
<script>
const { createApp, ref, computed, onMounted } = Vue;
// 创建一个 Vue 组件
const App = {
setup() {
const count = ref(0); // 使用 ref 来创建响应式变量
// 使用 computed 来创建一个计算属性
const doubledCount = computed(() => count.value * 2);
onMounted(() => {
console.log('Component is mounted!');
});
// 返回响应式数据和方法
return {
count,
doubledCount,
// 暴露函数供外部调用
increment: () => count.value++,
};
},
methods: {
proxit() {
this.increment()
}
},
};
// 创建并挂载 Vue 应用
const appm = createApp(App).mount('#app');
function ex() {
appm.increment()
}
</script>