把组件写作函数,并传递参数,在组件Create时接收并处理参数;

    function InitRoomSocket(key) {
    return new Vue({
    el: ‘#onlineUser’,
    template: <RoomSocket :room="room"></RoomSocket>,
    data: function () {
    return {
    room: null,
    }
    },
    created() {
    this.room = window.location.origin + key;
    }
    })
    }

    调用处如下:
    var ssss = InitRoomSocket(‘rsvedit’ + ‘?’ + rsvid);

    原始组件可以写到普通的js文件中,代码如下;
    (function () {
    function log(…args) {
    console.log(args);
    }
    function init(vm) {
    // const url = ws://${window.location.hostname}:7001/;
    const url = ws://localhost:7001/;
    // init
    const socket = io(url, {
    // 实际使用中可以在这里传递参数
    query: {
    room: vm.room,
    userid: vm.user.userid,
    username: vm.user.username,
    },
    transports: [‘websocket’]
    });
    socket.on(‘connect’, () => {
    const id = socket.id;
    log(‘#connect,’, id, socket);
    // 监听自身 id 以实现 p2p 通讯
    socket.on(id, msg => {
    log(‘#receive,’, msg);
    });
    });
    // 接收在线用户信息
    socket.on(‘online’, msg => {
    vm.update(msg);
    });
    // 系统事件
    socket.on(‘disconnect’, msg => {
    log(‘#disconnect’, msg);
    });
    socket.on(‘disconnecting’, () => {
    log(‘#disconnecting’);
    });
    socket.on(‘error’, () => {
    log(‘#error’);
    });
    vm.socket = socket;
    }
    Vue.component(‘RoomSocket’, {
    //template: /html/ <br /> //<div><br /> // <ul><br /> // <li v-for="item in list"<br /> // :key="item.userid">{{ item.username }}</li><br /> // </ul><br /> //</div>,
    template: /html/<br /><span><br /> [{{ names }}]正在查看本页<br /> </span>,
    props: {
    room: {
    type: String,
    default: () => {
    return window.location.href;
    }
    }
    },
    data() {
    return {
    list: []
    }
    },
    computed: {
    user() {
    return {
    userid: window._SESSION_USER.userid,
    username: window._SESSION_USER.username,
    }
    },
    names() {
    return this.list.map(t => t.username).join(‘,’);
    }
    },
    created() {
    init(this);
    },
    methods: {
    update(msg) {
    this.list = msg.clients;
    }
    },
    beforeDestroy() {
    this.socket && this.socket.disconnect();
    }
    });
    })();