PubNub Vue SDK 1.0.1

Unsupported SDK

PubNub no longer supports this SDK, but you are welcome to contribute.

Get Code: Source

https://github.com/pubnub/vue

Get Code: NPM

npm install pubnub-vue --save

Hello World

PubNub Vue is a wrapper of the PubNub JavaScript SDK version 4 that adds a few 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.

Differences in usage with native Javascript SDK

PubNub Vue is a wrapper of PubNub Javascript which offers the same features and in the same way as in the Javascript. If you have experience using the Javascript SDK, the Vue SDK will be fast to learn.

To learn more about PubNub JavaScript features, refer to the PubNub JavaScript SDK documentation.

Hello World Example

<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));
show all 24 lines

How to use PubNubVue

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 hook 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.

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

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
},
show all 16 lines

Events

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.

Triggering and listening to events for the subscribe method

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 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.

Triggering the events:

$pnGetMessage

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

ParameterTypeRequiredDefaultDescription
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'),
},
},
show all 22 lines

$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),
},
},
show all 27 lines

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),
},
},
show all 27 lines

$pnGetPresence

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

ParameterTypeRequiredDefaultDescription
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) {
show all 28 lines

Listening to the global status

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

ParameterTypeRequiredDefaultDescription
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) {
show all 27 lines

Publishing

ParameterTypeRequiredDefaultDescription
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)
);

Cleaning and Releasing

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.

ParameterTypeRequiredDefaultDescription
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.

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

Getting the history with autoload

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.

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

Unsubscribing

ParameterTypeRequiredDefaultDescription
argsObjectYesA hash of arguments to make the unsubscription.
instanceNameStringOptionaldefaultInstance to use into the component.
this.$pnUnsubscribe({
channels: ['ch1']
});

Getting the original instance

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();

Getting a new instance

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'),
};
},
show all 28 lines

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');

Copy and paste examples

For the next examples we will have to use the original instance in order to access to do not extended methods.

Init

When you install the PubNub plugin 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 Access Manager administrative operations.

Important

It is not a best practice to include the secretKey in client-side code for security reasons.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

Note

Set restore to true to allow catch-up on front-end applications.

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

import Vue from 'vue';
import PubNubVue from 'pubnub-vue';

Vue.use(PubNubVue, {
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
uuid: "myUniqueUUID",
ssl: true
});

Listeners

Add Listeners

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
show all 31 lines

Remove Listeners

import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

const existingListener = {
message: function() {
}
}

pubnub.removeListener(existingListener);

Listener status events

CategoryDescription
PNNetworkUpCategoryThe SDK detected that the network is online.
PNNetworkDownCategoryThe SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers.
PNNetworkIssuesCategoryA subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategoryAccess Manager permission failure.
PNMalformedResponseCategoryJSON parsing crashed.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategoryIf using decryption strategies and the decryption fails.
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.

Time

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);
}
});

Subscribe

Subscribe (listen on) a channel:

import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
channels: ['my_channel']
});
Note

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

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) {
show all 18 lines

Here Now

Get occupancy of who's here now on the channel by UUID:

Note

Requires you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.

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
}
);

Presence

Subscribe to real-time 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.

Note

Requires you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.

import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
Note

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.

History

Retrieve published messages from archival storage:

Note

Requires that the Message Persistence add-on is enabled for your key. 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
}
);

Unsubscribe

Stop subscribing (listening) to a channel:

import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.unsubscribe({
channels: ['my_channel']
});
Note

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.

Last updated on