0

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?

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • 1
    Yes, globals like `alert` or `console` are not available in the template. If you absolutely want them there, you can manually register them, have a look at https://stackoverflow.com/questions/51080447/how-can-i-use-console-log-or-console-error-in-a-vue-template – Moritz Ringler Apr 18 '23 at 15:26
  • @MoritzRingler How do I do it in composition api? – Ezzeldien Rashad Apr 18 '23 at 15:28
  • FYI: `alert()` is not a JavaScript function. It's a method of the global window API. It's provided by the browser and it not part of JavaScript. – Scott Marcus Apr 18 '23 at 15:50

1 Answers1

1

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>
yoduh
  • 7,074
  • 2
  • 11
  • 21