Tos*_*kan 14 vue.js vue-component vuejs2
我有一个Vue组件
<form @keydown="console.error($event.target.name);">
Run Code Online (Sandbox Code Playgroud)
给
app.js:47961 [Vue警告]:属性或方法“控制台”未在实例上定义,但在渲染期间被引用。
window.console也不起作用
在模板中使用控制台和窗口进行调试的正确方法是什么?
Wen*_* Du 17
使用 Vue ^3.3,您现在可以直接在模板中使用console
:
<template>
<!-- just works, no more `console` doesn't exist -->
<button @click="console.log">Log</button>
</template>
Run Code Online (Sandbox Code Playgroud)
如果使用 3.3 之前的 Vue,请执行以下操作:
const app = createApp(App)
app.config.globalProperties.console = console
Run Code Online (Sandbox Code Playgroud)
如果还使用 TypeScript:
// types.d.ts
export {}
declare module 'vue' {
interface ComponentCustomProperties {
console: Console
}
}
Run Code Online (Sandbox Code Playgroud)
如果使用 Vue 2,请执行以下操作:
// types.d.ts
export {}
declare module 'vue' {
interface ComponentCustomProperties {
console: Console
}
}
Run Code Online (Sandbox Code Playgroud)
console.*
在模板内部使用:
Vue.prototype.console = console
Run Code Online (Sandbox Code Playgroud)
为了不干扰渲染,请使用console.*
with ??
(或者||
如果使用 Vue 2,因为??
Vue 2 模板不支持):
<h1>{{ console.log(message) }}</h1>
Run Code Online (Sandbox Code Playgroud)
And*_*hiu 15
向模板提供全局对象的最简单方法是将它们放在 中computed
,如下所示:
console: () => console
. 同样适用于window
,
computed: {
console: () => console,
window: () => window,
}
Run Code Online (Sandbox Code Playgroud)
在这里看到它。
Un1*_*Un1 12
如果要内联运行而不是使用方法,只需将其添加this
到表单中:
Codepen: https ://codepen.io/x84733/pen/PaxKLQ ?editors = 1011
<form action="/" @keydown="this.console.log($event.target.name)">
First: <input type="text" name="fname"><br>
Second: <input type="text" name="fname2"><br>
</form>
Run Code Online (Sandbox Code Playgroud)
但是最好使用一种方法而不是内联运行函数,因此您可以更好地控制它:
<!-- Don't forget to remove the parenthesis -->
<form action="/" @keydown="debug">
First: <input type="text" name="fname"><br>
Second: <input type="text" name="fname2"><br>
</form>
...
methods: {
debug (event) {
console.log(event.target.name)
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
此外,如果您想从 {{ }} 访问控制台,您可以使用全局混入:
Vue.mixin({
computed: {
console: () => console
}
})
Run Code Online (Sandbox Code Playgroud)