vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装
npm install vuex@3 --save
src/store/index.js
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>