在 Vue 2 项目里引入 sockjs.min.js 、 stomp.min.js 和 jquery.js

介绍常见的两种

第一种方式适用于直接使用静态文件,第二种方式更符合现代前端开发规范,推荐使用第二种方式。

方式一:静态资源引入

  1. sockjs.min.js 、 stomp.min.js 和 jquery.js 文件放到项目的 public 目录(若使用 Vue CLI 创建的项目)。
  2. 在 public/index.html 文件里引入这些脚本。
DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %>title>
    
    <script src="sockjs.min.js">script>
    <script src="stomp.min.js">script>
    <script src="jquery.js">script>
  head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.strong>
    noscript>
    <div id="app">div>
    
  body>
html>

方式二:使用 npm 安装并在组件中引入

  1. 安装对应的依赖:npm install sockjs-client stompjs jquery
  2. 在需要使用这些库的组件里引入它们,例如在\src\views\test\test.vue 中:
<template>
<!-- ... existing code ... -->
</template>

<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import $ from 'jquery';

export default {
  // ... existing code ...
  methods: {
    // ... existing code ...
    sendName() {
      // 向服务端发送消息
      var name = $('#name').val();
      // 通过 stompClient.send 向 /hello (服务端)发送信息,对应控制器 @MessageMapping 中的定义
      this.stompClient.send("/hello", {}, JSON.stringify({ 'name': name }));
    },
    // ... existing code ...
  },
  // ... existing code ...
};
</script>

<style scoped>
/* ... existing code ... */
</style>

你可能感兴趣的:(前端,javascript,vue.js,jquery)