【问题标题】:show the whole text when clicking read more vuejs单击阅读更多vuejs时显示整个文本
【发布时间】:2021-08-09 22:58:13
【问题描述】:

我有一个描述部分,它只显示前 100 个单词,当点击阅读更多时,它会显示整个描述。

效果很好!我的问题是当点击阅读更多时,它会显示所有帖子的完整描述

代码:

    <template>
  <div class="page container">
    <div v-for="post in posts" :key="post.id" class="post">
        <p class="p h5">{{post.title}}</p>
        <p class="p" v-if="!readActivated">{{post.description.slice(0,100)}}<span class="read" v- 
        if="!readActivated" @click="activateReadMore">..read more</span></p>
        <p class="p" v-if="readActivated">{{post.description}}</p>
        <img class="img img-fluid" :src="'storage/'+post.path" alt="">
    </div>
  </div>
</template>

<script>
export default {
    data () {
        return{
            readActivated: false
        }
    },
    methods:{
        activateReadMore(){
            this.readActivated = true;
        }
    }
}
</script>

【问题讨论】:

    标签: html vue.js


    【解决方案1】:

    每个帖子都需要readActivated。 你的数据结构应该是这样的

    data() {
      return {
        posts: [
          {title: 'some text...', ..., readMore: false},
          {title: 'some text...', ..., readMore: false},
          {title: 'some text...', ..., readMore: false},
        ]
      }
    }
    

    在您的 HTML 中,它应该如下所示:

    <div class="page container">
        <div v-for="post in posts" :key="post.id" class="post">
            <p class="p h5">{{post.title}}</p>
            <p class="p" v-if="!readActivated">{{post.description.slice(0,100)}}<span class="read" 
               v-if="!readActivated" @click="post.readMore = !post.readMore">..read more</span></p> // <----- toggle each single readMore related to its item
            <p class="p" v-if="post.readMore">{{post.description}}</p> //<-- show only thoose which have "readMore" set to true 
            <img class="img img-fluid" :src="'storage/'+post.path" alt="">
        </div>
      </div>
    

    目前,您的所有帖子都将由一个 readActivated 控制,但每个帖子都需要有自己的 readActivated 才能按照您的意愿工作


    快速更新

    当从后端获取帖子时,您可以循环它们并为每个类似这样添加readActivated

    // fetch stuff... here 
    .then(res => {
      const posts = res.data
      for (const post of posts) {
        post.readActivated = false
      }
    })
    

    现在每个帖子都有自己的readActivated

    【讨论】:

    • 感谢 deniz,有道理,现在我应该回去将该属性添加到我的数据库中
    • 你也可以在前端添加这些道具。无需在您的数据库中为此添加道具
    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多