使用 v-model 到 div 标记时出现问题。显然, div 标签不允许 v-model ,我决定将我的评论部分创建为组件。由于 UI/UX 原因,我需要按原样分配此 div 文本区域。 textarea、input 等标签,据我所知,这些标签与 contenteditable="true"; 不兼容;当用户输入评论时,我需要扩展输入字段的高度。下面是我在父视图中导入的 vue 组件。
<!-- CommentSection.vue -->
<template>
<div id="chatId" contenteditable="true" placeholder="Leave a message" class="overflow-hidden block mx-4 text-left p-2.5 w-full text-sm text-gray-900 bg-white rounded-2xl border border-gray-300 focus:ring-blue-500 focus:border-blue-500"/>
</template>
<style>
#chatId[contenteditable="true"]:empty:not(:focus):before {
content: attr(placeholder)
}
</style>
在我的视图文件中,我将其导入并使用 v-model 到其中,就像这样。
<!--MainPage.vue-->
<template>
...
...
<CommentSection v-model="comment"/>
<button @click="submitPost()"> Submit </button>
...
...
...
</template>
<script>
import CommentSection from '@/components/CommentSection.vue'
export default{
name: 'MainPage',
data(){
return{
comment: '',
}
},
components: { CommentSection },
methods:{
submitPost(){
console.log(this.comment);
},
},
}
</script>
但是,当我检查控制台时,它给我值“null”或什么都没有。有办法解决这个问题吗?或者是我实现它的方式导致了问题。
编辑:这是在codesandbox中运行的代码。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我解决了你的问题,代码如下。希望对您有所帮助
通过在div标签中添加@,我们可以在change方法中看到标签内容的变化。在该方法中,使用emit$与其他组件共享其值
<!-- CommentSection.vue --> <template> <div id="chatId" @input="chanage" contenteditable="true" placeholder="Leave a message" class="overflow-hidden block mx-4 text-left p-2.5 w-full text-sm text-gray-900 bg-white rounded-2xl border border-gray-300 focus:ring-blue-500 focus:border-blue-500"/> </template> <script> export default { methods: { chanage (e) { this.$emit('value-div', e.target.textContent) } } } </script> <style> #chatId[contenteditable="true"]:empty:not(:focus):before { content: attr(placeholder) } </style>这里我们有 $emit 创建的 props,我们在 comment 变量中初始化它的值。其实它有类似v-model的功能。
<!--MainPage.vue--> <template> ... ... <CommentSection @value-div="(value)=>comment = value"/> <button @click="submitPost()"> Submit </button> ... ... ... </template> <script> import CommentSection from '@/components/CommentSection.vue' export default{ name: 'MainPage', data(){ return{ comment: '', } }, components: { CommentSection }, methods:{ submitPost(){ console.log(this.comment); }, }, } </script>