div 标签组件上的 V 模型
P粉550823577
P粉550823577 2024-01-07 08:47:44
0
1
448

使用 v-modeldiv 标记时出现问题。显然, div 标签不允许 v-model ,我决定将我的评论部分创建为组件。由于 UI/UX 原因,我需要按原样分配此 div 文本区域。 textareainput 等标签,据我所知,这些标签与 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中运行的代码。

P粉550823577
P粉550823577

全部回复(1)
P粉295728625

我解决了你的问题,代码如下。希望对您有所帮助

通过在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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!