alert() function not working on click event in vue.js

I am still a beginner in vue. I am using vue.js 3 SFC composition api. I have the following code:

<a href="#" @click.prevent="alert('default action prevented')">A link with prevent default</a>

When I click the link, I expect the alert box to appear, but I get the following error:

_ctx.alert is not a function
render/_cache[2]<@webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[3]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/App.vue?vue&type=template&id=7ba5bd90:19:106
withModifiers/<@webpack-internal:///./node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js:1632:12
callWithErrorHandling@webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:290:18
callWithAsyncErrorHandling@webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:298:38
invoker@webpack-internal:///./node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js:473:82

Why does this happen? How can I solve it?

>Solution :

SFC template has no context for window.alert(). Call it instead from within <script>

<a href="#" @click.prevent="showAlert">A link with prevent default</a>
<script setup>
function showAlert() {
  alert('default action prevented')
}
</script>

Leave a Reply