搜尋

首頁  >  問答  >  主體

div 標籤組件上的 V 模型

使用 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粉550823577P粉550823577394 天前550

全部回覆(1)我來回復

  • P粉295728625

    P粉2957286252024-01-08 00:12:08

    我解決了你的問題,程式碼如下。希望對您有幫助

    透過在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>

    回覆
    0
  • 取消回覆