【问题标题】:Passing the Div id to another vue component in laravel将 Div id 传递给 laravel 中的另一个 vue 组件
【发布时间】:2018-07-15 00:15:24
【问题描述】:

我在 laravel 中使用 vue js 创建了一个简单的实时聊天应用程序。 当有新数据时,我遇到了 div 自动滚动的问题。 我想要的是 div 在有新数据时自动向下滚动到 div 的底部。

这是我目前的代码。

Chat.vue 文件

<template>
  <div class="panel-block">
    <div class="chat" v-if="chats.length != 0" style="height: 400px;" id="myDiv">
      <div v-for="chat in chats" style="overflow: auto;" >
        <div class="chat-right" v-if="chat.user_id == userid">
          {{ chat.chat }}
        </div>
        <div class="chat-left" v-else>

          {{ chat.chat}}
        </div>
      </div>

    </div>
    <div v-else class="no-message">
      <br><br><br><br><br>
      There are no messages
    </div>
    <chat-composer v-bind:userid="userid" v-bind:chats="chats" v-bind:adminid="adminid"></chat-composer>
  </div>
</template>

<script>
  export default {
    props: ['chats','userid','adminid'],   
  }
</script>

ChatComposer.vue 文件

<template>

  <div class="panel-block field">
    <div class="input-group">
      <input type="text" class="form-control" v-on:keyup.enter="sendChat" v-model="chat">
      <span class="input-group-btn">
        <button class="btn btn-primary" type="button" v-on:click="sendChat">Send Chat</button>
      </span>
    </div>
  </div>

</template>

<script>
export default{
  props: ['chats','userid','adminid'],
  data() {
    return{
      chat: ''
    }
  },
  methods: {

    sendChat: function(e) {
      if(this.chat != ''){
        var data = {
          chat: this.chat,
          admin_id: this.adminid,
          user_id: this.userid
        }

        this.chat = ''; 

        axios.post('/chat/sendChat', data).then((response) => { 
          this.chats.push(data)
        })

        this.scrollToEnd();

      }
    },
    scrollToEnd: function() {       
      var container = this.$el.querySelector("#myDiv");
      container.scrollTop = container.scrollHeight;
    }

  }
}   

</script>

我正在将 Chat.vue 文件中的 div id 传递给 ChatComposer.vue 文件。

正如您在ChatComposer.vue 文件中看到的,有一个名为scrollToEnd 的函数,它从Chat.vue 文件中获取div id 的高度。

sendchat 函数被触发时,我调用了scrollToEnd 函数。

我猜他没有从 div id 中获取值,因为我收到一个错误 - 无法读取属性 'scrollHeight' of null。

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 用户props传值方法

标签: laravel vue.js vue-component


【解决方案1】:

this.$el.querySelector 的范围将仅限于 ChatComposer.vue,因此子组件无法访问父组件 #myDiv 的 div。

您可以在 ChatComposer 中触发如下事件

this.$emit('scroll');

在父组件中编写 ScollToEnd 方法并使用 $ref 分配新的高度

<chat-composer v-bind:userid="userid" v-bind:chats="chats" v-bind:adminid="adminid" @scroll="ScollToEnd"></chat-composer>

..

【讨论】:

  • 是的,这是一个很好的事件用例。我会创建一个专用的事件总线。要么使用状态管理器,要么使用像 vuex 这样的状态管理器。不过可能超出范围。
  • 如何使用 $ref 分配新高度以及应该将其放置在哪里?
  • 在 ScollToEnd 的父组件中,您可以访问 this.$ref.myDiv.scrollTop
猜你喜欢
  • 2020-12-24
  • 2018-10-21
  • 2018-06-20
  • 2019-10-07
  • 2018-07-19
  • 2022-11-01
  • 2021-11-06
  • 2019-06-25
  • 2020-07-14
相关资源
最近更新 更多