---
source_url: https://www.pubnub.com/docs/sdks/vue
title: Vue API & SDK Docs 1.0.1
updated_at: 2026-05-21T15:47:57.951Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Vue API & SDK Docs 1.0.1

:::warning Unsupported SDK
PubNub no longer supports this SDK. This wrapper was built for Vue 2, which has reached end-of-life.
For Vue 3 projects, use the [JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript) directly. The SDK integrates well with Vue 3's Composition API using `ref()` and `reactive()` for state management. For chat applications, consider the [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk) which works with any JavaScript framework.
Legacy Vue 2 contributions are [welcome on GitHub](https://github.com/pubnub/vue).
:::

## Get code: source

[https://github.com/pubnub/vue](https://github.com/pubnub/vue)

## Get code: NPM

```bash
npm install pubnub-vue --save
```

## Hello World

PubNub Vue is a wrapper of the PubNub JavaScript SDK [version 4](https://www.pubnub.com/docs/sdks/javascript) 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](https://www.pubnub.com/docs/sdks/javascript) documentation.

## Hello World example

```javascript
<template>
    <div id="app">
        <ol>
            <li v-for="msg in ch1">{{msg.message}}</li>
        </ol>
        <button v-on:click="push">push</button>
    </div>
</template>
```

```javascript
<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>
```

## 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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

```javascript
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
    },
});
```

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

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | String | Yes |  | `Channel` which will be listened. |
| callback | Function | Optional |  | Function which will be `invoked` as soon as received a new real time message. |
| keepMessage | Number | Optional |  | Number of messages which are `kept` and `rendered`. |
| instanceName | String | Optional | `default` | `Instance` to use into the component. |

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

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

```javascript
<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>
```

#### $pnGetPresence

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

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | `Channel` which will be listened. |
| `callback`Type: FunctionDefault: n/a | Function which will be `invoked` as soon as a new presence message is `invoked`. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

```javascript
<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>
```

#### 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](https://www.pubnub.com/docs/sdks/vue/api-reference/publish-and-subscribe#listeners)

| Parameter | Description |
| --- | --- |
| `callback`Type: FunctionDefault: n/a | Function which will be `invoked` as soon as a new change in the network. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

```javascript
<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>
```

### Publishing

| Parameter | Description |
| --- | --- |
| `args` *Type: ObjectDefault: n/a | A hash of `arguments` to make the unsubscription. |
| `callback`Type: FunctionDefault: n/a | Function which will be `invoked` after publishing the message. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

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

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | `Channel` which will be cleaned. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

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

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | `Channel` which will be released. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

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

| Parameter | Description |
| --- | --- |
| `args` *Type: ObjectDefault: n/a | A hash of `arguments` to make the subscription. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

```javascript
this.$pnSubscribe({
    channels: ['ch1'],
    autoload: 100
});
```

### Unsubscribing

| Parameter | Description |
| --- | --- |
| `args` *Type: ObjectDefault: n/a | A hash of `arguments` to make the unsubscription. |
| `instanceName`Type: StringDefault: `default` | `Instance` to use into the component. |

```javascript
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](https://www.pubnub.com/docs/sdks/javascript)

```javascript
const instance = this.$pnGetInstance();
```

or

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

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

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

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

or

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

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

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

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

#### Remove listeners

```javascript
import PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

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

pubnub.removeListener(existingListener);
```

#### Listener status events

| Category | Description |
| --- | --- |
| `PNNetworkUpCategory` | The SDK detected that the network is online. |
| `PNNetworkDownCategory` | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers. |
| `PNNetworkIssuesCategory` | A 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. |
| `PNReconnectedCategory` | The SDK was able to reconnect to PubNub. |
| `PNConnectedCategory` | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
| `PNAccessDeniedCategory` | Access Manager permission failure. |
| `PNMalformedResponseCategory` | JSON parsing crashed. |
| `PNBadRequestCategory` | The server responded with a bad response error because the request is malformed. |
| `PNDecryptionErrorCategory` | If using decryption strategies and the decryption fails. |
| `PNTimeoutCategory` | Failure to establish a connection to PubNub due to a timeout. |
| `PNRequestMessageCountExceedCategory` | The SDK announces this error if `requestMessageCountThreshold` is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
| `PNUnknownCategory` | Returned when the subscriber gets a non-200 HTTP response code from the server. |

### Subscribe

Subscribe (listen on) a channel:

```javascript
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](#listeners) for more details. Listeners should be added before calling the method.
:::

### Publish

Publish a message to a channel:

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

### 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?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) knowledge base article for details on enabling features.
:::

```javascript
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?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) knowledge base article for details on enabling features.
:::

```javascript
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](#listeners) 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?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

```javascript
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:

```javascript
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](#listeners) for more details. Listeners should be added before calling the method.
:::