后台开发人员你需要懂点vue-cli(四)

vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

安装

npm install vuex@3 --save

image-20231122142225849

src/store/index.js

image-20231122142304759

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
  //数据,相当于data
  state: {
    websocket: null,
    msg: ''
  },
  getters: {
    
  },
  //里面定义方法,操作state方发
  mutations: {
    
  },
  // 操作异步操作mutation
  actions: {
    
  },
  modules: {
    
  },
})

main.js

import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import router from './router'
import store from './store' //引入stroe

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(router)


new Vue({
  render: h => h(App),
  router,
  store  //引入store
}).$mount('#app')

引用stroe数据

使用this.$store.state.全局定义变量

created() {
    this.$store.state.websocket = new WebSocket('ws://localhost:9999//ws/older');
    this.$store.state.websocket.onopen = this.wsopen;
    this.$store.state.websocket.onmessage = this.wsmessage;
    this.$store.state.websocket.onclose = this.wsclose;
},
methods: {
    wsopen() {
        console.log("websocket连接成功.....")
    },
    wsclose() {
        console.log("websocket关闭成功.....")
    },
    wsmessage(event) {
        //获取后台交互
        console.log("===>" + event.data);
        let retVal = event.data;
        if (retVal.indexOf('wsSessionId') >= 0) {
            localStorage.setItem("wsSession", retVal);
        } else {
            this.$notify({
                title: '来自客服',
                message: event.data,
                duration: 3000
            });
        }
    },
    wssend() {
        this.$store.state.websocket.send(this.msg); //前端向后台发送信息
    },
    close() {
        console.log('关闭连接成功....')
    }
},
    destroyed() {
    localStorage.removeItem("wsSession")
    this.$store.state.websocket.onclose = close;
    }
}
</script>
<template>
    <div>
        <el-row>
            <el-col :span="18">
                <el-input v-model="$store.msg" placeholder="请问您还有什么问题?">
                </el-input>
            </el-col>
            <el-col :span="5">
                <el-button type="success" @click="wssend">发送给客服</el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script>
export default {
    data() {
        return {
        }
    },
    methods:{
        wssend() {
            this.$store.state.websocket.send(this.msg); //前端向后台发送信息
        }
    } 
}
</script>
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值