javascript - 父补偿。没有在听孩子 $emit
问题描述
我创建了一个表单组件Form.vue
,它是PostPage.vue
. 在“Form.vue”中,我想为父级发送 $emit 以更改 Prop 值btn-text
。
父组件PostPage.vue
:
<template>
<div id="post-page">
<div class="header-text pt-5 text-center">
<div class="h2 font-weight-bold">
Welcome to the DevTribe Community
</div>
<div class="h5 font-weight-bold">
Ask questions, share content, introduce yourself. Be nice!
</div>
</div>
<Form />
<!-- textarea-not-clear isn't catched here below -->
<Posts
:btn-text="btnText"
@textarea-not-clear="changeBtnText()"
/>
</div>
</template>
<script>
import Form from './PostPage/Form.vue';
import Posts from './PostPage/Posts.vue';
export default {
name: 'PostPage',
components: {
Form,
Posts
},
data() {
return {
}
},
methods: {
changeBtnText() {
console.log('tss');
}
}
}
</script>
<style lang="scss" scoped>
#post-page {
background-color: #ffffff;
height: 100%;
padding: 0 20%;
}
</style>
watch
如果 textarea 为空,则发射将在 a 中触发
子组件Form.vue
:
<template>
<div id="form">
<form class="text-area text-center mt-5 mx-auto w-100">
<div class="row">
<div class="col-12">
<textarea
v-model="textarea"
name="post-text"
rows="6"
class="w-100"
placeholder="Create a post..."
/>
</div>
<div class="col text-left">
<button
type="button"
class="btn btn-outline-primary"
>
Send
</button>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
name: 'Form',
data() {
return {
textarea: ''
}
},
watch: {
textarea: function() {
if (this.textarea !== '') {
this.$emit('textarea-not-clear', 'Join Discussion');
}
}
}
}
</script>
<style lang="scss" scoped>
.text-area {
height: 300px;
textarea {
border: solid black 1px;
}
button {
width: 120px;
}
}
</style>
我可以看到在 DevTool 的 Vue 扩展中触发的事件:
但由于某种原因,无法捕获该事件,changeBtnText()
内部的函数PostPage.vue
不会被触发,甚至没有给出console.log('test')
解决方案
第一件事。Form
不是一个好名称的组件,因为它与标准 HTML 元素冲突。我很惊讶您没有收到有关此的警告。见https://vuejs.org/v2/style-guide/#Multi-word-component-names-essential
接下来,您的事件的问题是您正在收听错误的组件。
<Form />
<!-- textarea-not-clear isn't catched here below -->
<Posts
:btn-text="btnText"
@textarea-not-clear="changeBtnText()"
/>
该事件正在由Form
组件触发,但您的侦听器位于Posts
组件上。
我还强烈建议您停止在组件上使用 id 并改用类进行样式设置。
推荐阅读
- powerbi - 当 SQL 中的语句连接多个表时,我有以下情况。我如何将其转换为 power bi DAX
- python - TypeError:不可散列的类型:'numpy.ndarray
- java - 找不到android媒体播放器文件
- java - Spring Web 应用程序。无法查看视图页面
- java - Android:如何旋转图像并设置填充片段?
- javascript - 如果存在单元号,则正则表达式从门牌号开始提取完整地址
- audio - 如何从 Amazon Fire TV 遥控器读取语音数据?
- django - 在 Django 1.11 和 2.0 中工作但在 Django 2.1-3.1 中没有数据内容形式的引导弹出窗口
- node.js - 如何从嵌套数组 mongodb 中获取单个匹配的文档?
- javascript - React JS:为什么第一次搜索时返回一个空数组?