英文:
Vue2 @click doesn't work with v-html in another component
问题
I have a sign up form and there is an Alert component to show the errors, one of the conditionals is "You already have an account click here to log in".
but the error messages are strings that are passed as props for the component "Alert" and the actions "click here" is a link.
<!-- Parent.vue -->
<Alert v-if="!!errorField" :message="errorList[errorField].message" />
here it is the message
// Parent.vue
errorList = {
hasAuth: {
message: `You already have an account <a @click.prevent="hasAuthClick()">click here</a> to log in`
}
}
the Alert component is simple it just receives the message as a prop and renders it with v-html
<!-- Child.vue -->
<span v-html="message"></span>
By investigations, I just realize that the link is not being compiled by vue, and that's why I can't use the @click on it, but I don't know how to make vue to compile.
英文:
I have a sign up form and there is an Alert component to show the errors, one of the conditionals is "You already have an account click here to log in".
but the error messages are strings that are passed as props for the component "Alert" and the actions "click here" is a link.
<!-- Parent.vue -->
<Alert v-if="!!errorField" :message="errorList[errorField].message" />
here it is the message
// Parent.vue
errorList = {
hasAuth: {
message: `You already have an account <a @click.prevent="hasAuthClick()">click here</a> to log in`
}
}
the Alert component is simple it just recieve the message as prop and render with v-html
<!-- Child.vue -->
<span v-html="message"></span>
By investigations, I just realize that the link is not being compiled by vue, and that's why I can't use the @click on it, but I don't know how to make vue to compile.
答案1
得分: 1
它将不适用于 v-html
指令,您应该使用Vue 插槽 或 渲染函数。
我更喜欢使用插槽
来实现这个。
Alert.vue
<template>
<div>
<slot>默认插槽内容</slot>
<slot name="message">消息插槽内容</slot>
</div>
</template>
然后
<alert>
默认插槽内容
<template #message>
您已经有一个帐户 <a @click.prevent="hasAuthClick()">点击这里</a> 登录
</template>
</alert>
请注意,函数 hasAuthClick()
应该在 Alert.vue
外部的父组件/应用中定义。
查看我的另一个回答,有关渲染函数
的内容:
英文:
It will not work with v-html
directive and you should use Vue Slots or Render Functions
I would rather use Slots
for this.
Alert.vue
<template>
<div>
<slot>default slot</slot>
<slot name="message">message slot</slot>
</div>
</template>
and then
<alert>
default slot content
<template #message>
You already have an account <a @click.prevent="hasAuthClick()">click here</a> to log in
</template>
</alert>
Pay attention, the function hasAuthClick()
should be defined outside Alert.vue
, in the parent component/app.
Check my another antwort for the Render Functions
Adding custom HTML element inside template using functions Vue.js
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论