Home  >  Article  >  Web Front-end  >  The combination of Vue.js and Elixir language realizes real-time chat and communication applications

The combination of Vue.js and Elixir language realizes real-time chat and communication applications

WBOY
WBOYOriginal
2023-07-30 09:12:41851browse

The combination of Vue.js and Elixir language realizes real-time chat and communication applications

With the popularity of mobile Internet, real-time chat and communication applications are becoming more and more popular. Vue.js and Elixir are two technologies that have attracted much attention in recent years. They are leaders in the front-end and back-end fields respectively. This article will introduce how to build a real-time chat and communication application by combining Vue.js and Elixir.

First of all, we need to build a basic communication backend and use Elixir to implement it. Elixir is a functional programming language based on the Erlang virtual machine with strong concurrency capabilities and fault tolerance. We can use the Phoenix framework to quickly build an efficient web application.

  1. First, install Elixir and Phoenix framework. Run the following command in the command line:

    $ mix archive.install hex phx_new 1.5.8
    $ mix phx.new chat_app
  2. Go into the project directory and create a main part of the chat function:

    $ cd chat_app
    $ mix phx.gen.live Chat Room rooms name:string
    $ mix ecto.migrate

The above command will generate Chat related models, controllers and views and doing database migrations.

  1. Start the Elixir backend server:

    $ mix phx.server

    Now, we have completed the setup of the Elixir backend.

Next, we will use Vue.js to build the front-end interface and communicate with the backend in real time. Vue.js is a lightweight JavaScript framework focused on building user interfaces.

  1. Create a Vue.js project and install some necessary dependencies.

    $ vue create chat_app_frontend
    $ cd chat_app_frontend
    $ npm install axios vue-axios pusher-js laravel-echo
  2. Open the src/main.js file and add the following code:

    import Vue from 'vue'
    import App from './App.vue'
    import axios from 'axios'
    import VueAxios from 'vue-axios'
    import Echo from 'laravel-echo'
    
    Vue.config.productionTip = false
    
    Vue.use(VueAxios, axios)
    
    window.Echo = new Echo({
     broadcaster: 'pusher',
     key: 'YOUR_PUSHER_KEY',
     cluster: 'YOUR_PUSHER_CLUSTER',
     encrypted: true
    });
    
    new Vue({
      render: h => h(App),
    }).$mount('#app')

The above code will set up axios and Echo instances for use with Communicate in the background.

  1. Create a Chat component in the src/components directory and add the following code:

    <template>
      <div>
     <h2>Chat Room</h2>
     <div v-for="message in messages" :key="message.id">
       <strong>{{ message.username }}</strong>: {{ message.content }}
     </div>
     <form @submit.prevent="sendMessage">
       <input type="text" v-model="newMessage" placeholder="Enter message">
       <button type="submit">Send</button>
     </form>
      </div>
    </template>
    
    <script>
    export default {
      data() {
     return {
       messages: [],
       newMessage: ''
     }
      },
      created() {
     window.Echo.join('chat')
       .here((users) => {
         console.log(users);
       })
       .joining((user) => {
         console.log(user);
       })
       .leaving((user) => {
         console.log(user);
       })
       .listen('NewMessage', (message) => {
         this.messages.push(message);
       });
      },
      methods: {
     sendMessage() {
       axios.post('/api/messages', { content: this.newMessage })
         .then(() => {
           this.newMessage = '';
         })
         .catch((error) => {
           console.error(error);
         });
     }
      }
    }
    </script>

The above code will display the chat room content and Implement the function of sending and receiving messages.

  1. Edit the src/App.vue file, import and add the Chat component to the template:

    <template>
      <div id="app">
     <Chat />
      </div>
    </template>
    
    <script>
    import Chat from './components/Chat.vue'
    
    export default {
      name: 'App',
      components: {
     Chat
      }
    }
    </script>

At this point, the front-end code has been Finish.

Finally, we need to provide an API interface in the Elixir backend to handle front-end requests:

  1. Open the chat_app/lib/chat_web/router.ex file and add The following code:

    scope "/api", ChatWeb do
      pipe_through :api
    
      resources "/messages", MessageController, except: [:new, :edit]
    end

The above code will generate the API interface related to the message.

  1. Create the chat_app/lib/chat_web/controllers/message_controller.ex file and add the following code:

    defmodule ChatWeb.MessageController do
      use ChatWeb, :controller
    
      alias ChatWeb.Message
    
      def create(conn, %{"content" => content}) do
     changeset = Message.changeset(%Message{}, %{content: content})
     
     case Repo.insert(changeset) do
       {:ok, message} ->
         ChatWeb.Endpoint.broadcast("chat", "new_message", %{id: message.id, content: message.content, username: "Anonymous"})
         conn |> json(%{status: "ok"})
       _ ->
         conn |> json(%{status: "error"})
     end
      end
    end

The above code will handle the front-end sending POST request for the message and broadcast the message content to all clients connected to the "chat" channel.

So far, we have completed the combination of Vue.js and Elixir to implement real-time chat and communication applications. Using Vue.js as the front-end framework, you can display chat content and send messages in real time; using Elixir as the back-end framework, you can efficiently handle the reception and broadcast of messages. By combining Vue.js and Elixir, we can build powerful and performant real-time chat and messaging applications.

I hope this article will be helpful to readers who want to understand and use Vue.js and Elixir for application development.

The above is the detailed content of The combination of Vue.js and Elixir language realizes real-time chat and communication applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn