VuePubNub Vue V4 SDK 1.0.1

npm install pubnub-vue --save

PubNub Vue is a wrapper of PubNub JavaScript SDK version 4 that adds a few of extra features to simplify the integration with Vue:

  • Trigger Events: $pnGetMessage, $pnGetPresence, $pnGetStatus will make your life easier in the Vue' World.
  • Autoload: An easy and fast way to recovery the history messages of your channel.

You can still use the native PubNub JavaScript SDK if you feel this will be more suitable for your situation.

PubNub Vue is a wrapper of PubNub Javascript, which offers the same feature and in the same way as Javascript SDK makes, So if you have experience using Javascript SDK will be fast to learn the features included for Vue SDK in other way if you want to learn more about PubNub JavaScript features refer to native PubNub JavaScript SDK manual.

<template>
    <div id="app">
        <ol>
            <li v-for="msg in ch1">{{msg.message}}</li>
        </ol>
        <button v-on:click="push">push</button>
    </div>
</template>
<script>
    export default {
        name: 'app',
        data() {
            return {
                ch1: this.$pnGetMessage('ch1'),
            },
        },
        methods: {
            push() {
                this.$pnPublish({
                    channel: 'ch1',
                    message: Date.now()
                },
                (status, response) => console.log(status, response));
            },
        },
        mounted() {
            this.$pnSubscribe({
				channels: ['ch1']
			});
        },
    };
</script>

In order to get the integration between your Vue's Component and PubNub, PubNubVue will be the way to get this without any kind of difficulty or extra job when you need render data in your UI.

 
  • An instance of PubNubVue can be spread over all components hierarchically using the instance by default or assigning one instance for each component.
  • Use the hook mounted for subscribing from a component.
  • Use the hood created for invoking the extended method: $pnGetInstance in order to create new instances.
  • You can still use the native PubNub JavaScript SDK if you feel this will be more suitable for your situation.
import Vue from 'vue';
import PubNubVue from 'pubnub-vue';
import App from './App';

Vue.use(PubNubVue, {
    subscribeKey: 'YOUR SUBSCRIBE KEY HERE',
    publishKey: 'YOUR PUBLISH KEY HERE'
});

new Vue({
    el: '#app',
    template: '<App/>',
    components: {
        App
    },
});

Another key feature of this SDK is the ability to use trigger events, in addition to pass callbacks, getting all messages through states and inject them directly in your UI of your Vue Component in an easy and fast way.

With the trigger events you can find a way to get real time apps with PubNub Vue very fast, because it will be resolved the synchronization between the data received and the user interface through associating a channel to a reactive property to the root data object.

The trigger events are methods which encapsulate the events (message, presence and status) from Javascript SDK v4 with extra functionality to offer integration and get the process of development faster because will be resolved different scenarios which you can find when you are working with Vue.

Use $pnGetMessage to associate a channel subscribed to a reactive property and start to display messages as soon as these are received.

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel which will be listened.
callbackFunctionOptionalFunction which will be invoked as soon as received a new real time message.
keepMessageNumberOptionalNumber of messages which are kept and rendered.
instanceNameStringOptionaldefaultInstance to use into the component.
<template>
    <div id="app">
        <ol>
            <li v-for="msg in ch1">{{ msg.message }}</li>
        </ol>
    </div>
</template>
<script>
    export default {
        name: 'app',
        data() {
            return {
                ch1: this.$pnGetMessage('ch1'),
            },
        },
        mounted() {
            this.$pnSubscribe({
                channels: ['ch1', 'ch2']
            });
        },
    };
</script>

$pnGetMessage will receive a second parameter which is a callback function that is going to be invoked as soon as received a new real time message. This will allow to apply transformation or manipulate of somehow to each message or implement a custom mechanism to render these.

<template>
    <div id="app">
        <ol>
            <li v-for="msg in ch1">{{ msg.message }}</li>
        </ol>
    </div>
</template>
<script>
    export default {
        name: 'app',
        data() {
            return {
                ch1: this.$pnGetMessage('ch1', this.receptor),
            },
        },
        methods: {
            receptor(msg) {
                msg.message = `sent - ${msg.message}`;
            },
        },
        mounted() {
            this.$pnSubscribe({
                channels: ['ch1', 'ch2']
            });
        },
    };
</script>

When you are using $pnGetMessage this going to keep the latest 100 messages received by default. But you can change this value when you attach the channel with $pnGetMessage.

<template>
    <div id="app">
        <ol>
            <li v-for="msg in ch1">{{ msg.message }}</li>
        </ol>
    </div>
</template>
<script>
    export default {
        name: 'app',
        data() {
            return {
                ch1: this.$pnGetMessage('ch1', null, 10),
            },
        },
        methods: {
            receptor(msg) {
                msg.message = `sent - ${msg.message}`;
            },
        },
        mounted() {
            this.$pnSubscribe({
                channels: ['ch1', 'ch2']
            });
        },
    };
</script>

To use $pnGetPresence you will have to add the argument withPresence: true when you are subscribing your channels.

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel which will be listened.
callbackFunctionOptionalFunction which will be invoked as soon as a new presence message is invoked.
instanceNameStringOptionaldefaultInstance to use into the component.
<template>
    <div id="app">
        <span>occupancy: {{ occupancy }}</span>
    </div>
</template>
<script>
    export default {
        name: 'app',
        data() {
            return {
                occupancy: 0,
            };
        },
        methods: {
            presence(ps) {
                this.occupancy = ps.occupancy;
                console.log(ps);
            },
        },
        mounted() {
            this.$pnSubscribe({
                channels: ['ch1'],
                withPresence: true
            });
            this.$pnGetPresence('ch1', this.presence);
        },
    };
</script>

The $pnGetStatus which is wrapper of the status listener, you can receive different events such as: when the network is online (PNNetworkUpCategory), when the SDK is connected to a set of channels (PNConnectedCategory), etc... See the list of events available in the API Reference.

ParameterTypeRequiredDefaultsDescription
callbackFunctionOptionalFunction which will be invoked as soon as a new change in the network.
instanceNameStringOptionaldefaultInstance to use into the component.
<template>
    <div id="app">
        <span>category: {{ category }}</span>
    </div>
</template>
<script>
export default {
    name: 'app',
    data() {
        return {
            category: '',
        };
    },
    methods: {
        status(st) {
            console.log(st);
            this.category = st.category;
        },
    },
    mounted() {
        this.$pnSubscribe({
            channels: ['ch1']
        });
        this.$pnGetStatus(this.status);
    },
};
</script>
ParameterTypeRequiredDefaultsDescription
argsObjectYesA hash of arguments to make the unsubscription.
callbackFunctionOptionalFunction which will be invoked after publishing the message.
instanceNameStringOptionaldefaultInstance to use into the component.
this.$pnPublish(
    {
        channel: 'ch1',
        message: Date.now()
    },
    (status, response) => console.log(status, response)
);

You can execute clean to remove all message cached in the state of the Component by the instance in running time without affecting the capture of new incoming messages for the trigger events.

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel which will be cleaned.
instanceNameStringOptionaldefaultInstance to use into the component.
this.$pnClean('ch1');

You can execute release if you want to remove all message cached and stop of capturing new incoming messages for the trigger events.

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel which will be released.
instanceNameStringOptionaldefaultInstance to use into the component.
this.$pnRelease('ch1');

At the moment that you are subscribing a channel you can pass the optional parameter autoload this value has to contain a value from 1 to 100 in order to retrieve the last messages published in the channel. When the $pnGetMessage is called this going to retrieve the history. You can use a callback to know when the retrieving process has finished.

ParameterTypeRequiredDefaultsDescription
argsObjectYesA hash of arguments to make the subscription.
instanceNameStringOptionaldefaultInstance to use into the component.
this.$pnSubscribe({
    channels: ['ch1'],
    autoload: 100
});
ParameterTypeRequiredDefaultsDescription
argsObjectYesA hash of arguments to make the unsubscription.
instanceNameStringOptionaldefaultInstance to use into the component.
this.$pnUnsubscribe({
    channels: ['ch1']
});

The functions described above are the most used but if you need to use some of the rest which are not found like extended functions in Vue, you can continue to access to them through the original instance which is going to offer all capabilities that you can find using Javascript SDK.

const instance = this.$pnGetInstance();

or

import PubNubVue from 'pubnub-vue';

const instance = PubNubVue.getInstance();
 Use the hook created to initialize new instances.

The $pnGetInstance method will return the main instance which be created by default but if we need to create an additional instance, we can pass as a parameter the name of a new one instance and with this same name, you will have the capability of retrieving from other component inside of our application.

<template>
    <div id="app">
        <ol>
            <li v-for="msg in ch1">{{ msg.message }}</li>
        </ol>
    </div>
</template>
<script>
export default {
    name: 'app',
    data() {
        return {
            ch1: this.$pnGetMessage('ch1', null, 10, 'instance2'),
        };
    },
    mounted() {
        this.$pnSubscribe(
            {
                channels: ['ch1']
            },
            'instance2'
        );
    },
    created() {
        this.$pnGetInstance('instance2');
    },
};
</script>

The previous example will listen to the channel ch1 without using callback function and it is going to render only the last 10 message received with the usage of the instance instance2.

this.$pnGetMessage(
    'ch1',
    null,
    10,
    'instance2'
)

By default all extended methods use the instance by default if you need to use some of them with other instance you will have to set as parameter the name of the instance to use when you invoke the method according to list of parameter that receives.

const instance2 = PubNubVue.getInstance('instance2');

or

const instance = this.$pnGetInstance('instance2');
 For the next examples we will have to use the original instance in order to access to do not extended methods.
When you install like a plugin PubNub. Only the subscribeKey is mandatory but if you want to publish from this instance, you have to set the secretKey in addition if you wish to perform PAM administrative operations.
 It is not the best practice to include secretKey in client-side code for security reason.
 Set restore as true to allow catch up on the front-end applications.
import Vue from 'vue';
import PubNubVue from 'pubnub-vue';

Vue.use(PubNubVue, {
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    ssl: true
});
A listener lets you to catch up real time messages, get presence and status information if you do not want to use the $pnGetMessage, $pnGetPresence, $pnGetStatus methods. Remember add a listener before subscribing a channel.
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.addListener({
    message: function(m) {
        // handle message
        var channelName = m.channel; // The channel for which the message belongs
        var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
        var pubTT = m.timetoken; // Publish timetoken
        var msg = m.message; // The Payload
        var publisher = m.publisher; //The Publisher
    },
    presence: function(p) {
        // handle presence
        var action = p.action; // Can be join, leave, state-change or timeout
        var channelName = p.channel; // The channel for which the message belongs
        var occupancy = p.occupancy; // No. of users connected with the channel
        var state = p.state; // User State
        var channelGroup = p.subscription; //  The channel group or wildcard subscription match (if exists)
        var publishTime = p.timestamp; // Publish timetoken
        var timetoken = p.timetoken;  // Current timetoken
        var uuid = p.uuid; // UUIDs of users who are connected with the channel
    },
    status: function(s) {
        var affectedChannelGroups = s.affectedChannelGroups;
        var affectedChannels = s.affectedChannels;
        var category = s.category;
        var operation = s.operation;
    }
});
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

const existingListener = {
    message: function() {
    } 
}
 
pubnub.removeListener(existingListener);
CategoriesDescription
PNNetworkUpCategory
SDK detected that network is online.
PNNetworkDownCategory
SDK detected that network is down.
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategory
PAM permission failure.
PNMalformedResponseCategory
JSON parsing crashed.
PNBadRequestCategory
Server rejected the request.
PNDecryptionErrorCategory
If using decryption strategies and the decryption fails.
PNTimeoutCategory
Failure to establish connection due to timeout.
Call time() to verify the client connection to the origin:
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.time(function(status, response) {
    if (status.error) {
        // handle error if something went wrong based on the status object
    } else {
        console.log(response.timetoken);
    }
});
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({ 
	channels: ['my_channel'] 
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Publish a message to a channel:
const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: {
            such: 'object'
        },
        channel: 'ch1',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: {
            "cool": "meta"
        } // publish extra meta with the request
    },
    function(status, response) {
        // handle status, response
    }
);
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.hereNow(
    {
        channels: ["ch1"], 
        channelGroups : ["cg1"],
        includeUUIDs: true,
        includeState: true
    },
    function(status, response) {
        // handle status, response
    }
);
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({ 
	channels: ['my_channel'], 
	withPresence: true 
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.history(
    {
        channel: 'history_channel',
        count: 100, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
    },
    function(status, response) {
        // handle status, response
    }
);
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.unsubscribe({
    channels: ['my_channel']
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.