div 標籤組件上的 V 模型
P粉550823577
P粉550823577 2024-01-07 08:47:44
0
1
466

使用 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學習者快速成長!