---
source_url: https://www.pubnub.com/docs/sdks/vue/api-reference/publish-and-subscribe
title: Publish/Subscribe API for Vue SDK
updated_at: 2026-05-22T11:08:10.931Z
---

> 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


# Publish/Subscribe API for Vue SDK

PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.

For higher-level conceptual details on publishing and subscribing, refer to [Connection Management](https://www.pubnub.com/docs/general/setup/connection-management) and to [Publish Messages](https://www.pubnub.com/docs/general/messages/publish).

## Publish

The `publish()` function sends a message to all channel subscribers. PubNub replicates the message and delivers it to all subscribed clients on that channel. To publish a message you must first specify a valid `publishKey` at initialization.

Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.

##### Publish anytime

It's not required to be subscribed to a channel in order to publish to that channel.

##### Message data

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. `data` should not contain special Vue classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

:::warning Don't Use JSON.stringify!
It is important to note that you should not use `JSON.stringify()` when sending signals/messages via PubNub. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
:::

##### Message size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

##### Message too large error

```javascript
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
```

See [Message size limits](https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-Message-Payload-Size-Before-Publish).

##### Message publish rate

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

##### Publishing to multiple channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

##### Publishing messages reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

* Publish to any given channel in a serial manner (not concurrently).
* Check that the return code is success (e.g. `[1,"Sent","136074940..."]`)
* Publish the next message only after receiving a success return code.
* If a failure code is returned (`[0,"blah","<timetoken>"]`), retry the publish.
* Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
* Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.

### Method(s)

To `Publish a message` you can use the following method(s) in the Vue SDK:

```javascript
publish( {Object message, String channel, Boolean storeInHistory, Boolean sendByPost, Object meta, Number ttl }, Function callback )
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| message | Object | Yes |  | The `message` may be any valid JSON type including objects, arrays, strings, and numbers. |
| channel | String | Yes |  | Specifies `channel` name to publish messages to. |
| storeInHistory | Boolean | Optional | `true` | If `true` the messages are stored in history. If `storeInHistory` is not specified, then the history configuration on the key is used. |
| sendByPost | Boolean | Optional | `false` | When `true`, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request, instead of the query string when HTTP GET is used. Also the messages are compressed thus reducing the size of the messages. Using HTTP POST to publish messages adheres to RESTful API best practices. |
| meta | Object | Optional |  | Publish extra `meta` with the request. |
| ttl | Number | Optional |  | Set a per message time to live in Message Persistence. If storeInHistory = true, and ttl = 0, the message is stored with no expiry time., If storeInHistory = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal., If storeInHistory = false, the ttl parameter is ignored., If ttl is not specified, then expiration of the message defaults back to the expiry value for the key. |
| callback | Function | Optional |  | Executes on a successful/unsuccessful `publish`. |

### Sample code

#### Publish a message to a channel

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: {
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default Message Persistence options
        meta: {
            cool: 'meta'
        }   // publish extra meta with the request
    },
    function(status, response) {
        if(status.error) {
            // handle error
            console.log(status);
        } else {
            console.log('message Published w/ timetoken', response.timetoken);
        }
    }
);
```

:::note
Before running the above publish example, either using the [Debug Console](https://www.pubnub.com/docs/console) or in a separate script running in a separate terminal window, [subscribe to the same channel](#subscribe) that is being published to.
:::

### Response

```json
type PublishResponse = {
    timetoken: number
}
```

### Other examples

#### Publish a JSON serialized message

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

const pubnub = PubNubVue.getInstance();

const newMessage = {
    text: 'Hi There!'
};

pubnub.publish(
    {
        message: newMessage,
        channel: 'my_channel'
    },
    function(status, response) {
        if (status.error) {
            console.log('publishing failed w/ status: ', status);
        } else {
            console.log('message published w/ server response: ', response);
        }
    }
);
```

#### Store the published message for 10 hours*

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: 'hello!',
        channel: 'my_channel',
        storeInHistory: true,
        ttl: 10
    },
    function(status, response) {
        if (status.error) {
            console.log('publishing failed w/ status: ', status);
        } else {
            console.log('message published w/ server response: ', response);
        }
    }
);
```

#### Publish successful

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: 'hello world!',
        channel: 'ch1'
    },
    function(status, response) {
        console.log(status); // {error: false, operation: "PNPublishOperation", statusCode: 200}
        console.log(response); // {timetoken: "14920301569575101"}
    }
);
```

#### Publish unsuccessful by network down*

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: 'hello world!',
        channel: 'ch1'
    },
    function(status, response) {
        console.log(status);
        // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"}
        console.log(response); // undefined
    }
);
```

#### Publish unsuccessful by initialization without publishKey

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: 'hello world!',
        channel: 'ch1'
    },
    function(status, response) {
        console.log(status);
        // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"}
        console.log(response); // undefined
    }
);
```

#### Publish unsuccessful by missing channel

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        message: 'hello world!'
    },
    function(status, response) {
        console.log(status); // {message: "Missing Channel", type: "validationError", error: true}
        console.log(response); // undefined
    }
);
```

#### Publish unsuccessful by missing message

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

const pubnub = PubNubVue.getInstance();

pubnub.publish(
    {
        channel: 'ch1'
    },
    function(status, response) {
        console.log(status);  // {message: "Missing Message", type: "validationError", error: true}
        console.log(response); // undefined
    }
);
```

#### Sample code using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    message: {
        such: 'object'
    },
    channel: 'my_channel',
    sendByPost: false, // true to send via post
    storeInHistory: false, //override default Message Persistence options
    meta: {
        cool: 'meta'
    }   // publish extra meta with the request
}).then((response) => {
    console.log(response)
}).catch((error) => {
    console.log(error)
});
```

#### Publish a JSON serialized message using promises

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

const pubnub = PubNubVue.getInstance();

const newMessage = {
    text: 'Hi There!'
}
pubnub.publish({
    message: newMessage,
    channel: 'my_channel'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    console.log(error)
});
```

#### Store the published message for 10 hours using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    message: 'hello!',
    channel: 'my_channel',
    storeInHistory: true,
    ttl: 10
}).then((response) => {
    console.log(response)
}).catch((error) => {
    console.log(error)
});
```

#### Publish successful using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    message: 'hello world!',
    channel: 'ch1'
}).then((response) => {
    console.log(response); // {timetoken: "14920301569575101"}
}).catch((err) => {
    console.log(err);
});
```

#### Publish unsuccessful by network down using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    message: 'hello world!',
    channel: 'ch1'
}).then((response) => {
    console.log(response);
}).catch((err) => {
    console.log(err);
    // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"}
});
```

#### Publish unsuccessful by initialization without publishKey using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    message: 'hello world!',
    channel: 'ch1'
}).then((response) => {
    console.log(response);
}).catch((err) => {
    console.log(err);
    // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"}
});
```

#### Publish unsuccessful by missing channel using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    message: 'hello world!'
}).then((response) => {
    console.log(response);
}).catch((err) => {
    console.log(err);
    // {message: "Missing Channel", type: "validationError", error: true}
});
```

#### Publish unsuccessful by missing message using promises

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

const pubnub = PubNubVue.getInstance();

pubnub.publish({
    channel: 'ch1'
}).then((response) => {
    console.log(response);
}).catch((err) => {
    console.log(err);
    // {message: "Missing Message", type: "validationError", error: true}
});
```

## Fire

The fire endpoint allows the client to send a message to Functions Event Handlers and [Illuminate](https://www.pubnub.com/docs/illuminate/business-objects/external-data-sources). These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via `fire()` isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.

### Method(s)

To `Fire a message` you can use the following method(s) in the Vue SDK:

```javascript
fire( {Object message, String channel, Boolean sendByPost, Object meta}, Function callback )
```

| Parameter | Description |
| --- | --- |
| `message` *Type: ObjectDefault: n/a | The `message` may be any valid JSON type including objects, arrays, strings, and numbers. |
| `channel` *Type: StringDefault: n/a | Specifies `channel` name to publish messages to. |
| `sendByPost`Type: BooleanDefault: `false` | If `true` the messages sent via POST. |
| `meta`Type: ObjectDefault: n/a | Publish extra `meta` with the request. |
| `callback`Type: FunctionDefault: n/a | Executes on a successful/unsuccessful `publish`. |

### Sample code

#### Fire a message to a channel

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

const pubnub = PubNubVue.getInstance();

pubnub.fire(
    {
        message: {
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        meta: {
            cool: 'meta'
        }   // fire extra meta with the request
    },
    function(status, response) {
        if (status.error) {
            // handle error
            console.log(status);
        } else {
            console.log("message published w/ timetoken", response.timetoken);
        }
    }
);
```

### Other examples

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

const pubnub = PubNubVue.getInstance();

pubnub.fire({
    message: {
        such: 'object'
    },
    channel: 'my_channel',
    sendByPost: false, // true to send via post
    meta: {
        cool: 'meta'
    }   // fire extra meta with the request
}).then((response) => {
    console.log(response);
}).catch((error) => {
    console.log(error);
});
```

## Signal

The `signal()` function is used to send a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of `64` bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please [contact support](https://www.pubnub.com/docs/mailto:support@pubnub.com).

### Method(s)

To `Signal a message` you can use the following method(s) in the Vue SDK:

```javascript
signal( {String message, String channel}, Function callback )
```

| Parameter | Description |
| --- | --- |
| `message` *Type: String | The `message` may be any valid JSON type including objects, arrays, strings, and numbers. |
| `channel` *Type: String | Specifies `channel` name to send messages to. |
| `callback`Type: Function | Executes on a successful/unsuccessful `send`. |

### Sample code

#### Signal a message to a channel

```javascript
pubnub.signal({
    message: 'hello',
    channel: 'foo',
});
```

### Response

```javascript
type SignalResponse = {
    timetoken: number
}
```

## Subscribe

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified `channel`. To subscribe to a `channel` the client must send the appropriate `subscribeKey` at initialization.

By default a newly subscribed client will only receive messages published to the channel after the `subscribe()` call completes.

:::tip
You can be notified of connectivity via the listener, on establishing connection the `statusEvent.category` returns `PNConnectedCategory`.
By waiting for the connect event to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the `subscribe` has completed.
:::

:::warning
**Unsubscribing** from all channels, and then **subscribing** to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received `timetoken` and thus, there could be some gaps in the subscription that may lead to message loss.
:::

### Method(s)

To `Subscribe to a channel` you can use the following method(s) in the Vue SDK:

```javascript
subscribe({Array channels, Array channelGroups, Boolean withPresence, Number timetoken})
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: ArrayDefault: n/a | Specifies the `channels` to subscribe to. It is possible to specify multiple `channels` as a list or as an array. |
| `channelGroups`Type: ArrayDefault: n/a | Specifies the `channelGroups` to subscribe to. |
| `withPresence`Type: BooleanDefault: `false` | If `true` it also subscribes to presence instances. |
| `timetoken`Type: NumberDefault: n/a | Specifies `timetoken` from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. |

### Sample code

Subscribe to 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.
:::

### Returns

| Object | Description |
| --- | --- |
| `category` | `PNConnectedCategory` |
| `operation` | `PNSubscribeOperation` |
| `affectedChannels` | The channels affected in the operation, of type array. |
| `subscribedChannels` | All the current subscribed channels, of type array. |
| `affectedChannelGroups` | The channel groups affected in the operation, of type array. |
| `lastTimetoken` | The last timetoken used in the subscribe request, of type long. |
| `currentTimetoken` | The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long. |

```json
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
```

#### Subscribe message response

| Object | Description |
| --- | --- |
| `channel` | The `channel` for which the message belongs. |
| `subscription` | The `channel group` or wildcard subscription match (if exists). |
| `timetoken` | Publish `timetoken`. |
| `message` | The `payload`. |
| actualChannel | Deprecated. Use property `channel`. |
| subscribedChannel | Deprecated. Use property `subscription`. |

```json
{
    actualChannel: null,
    channel: "my_channel_1",
    message: "Hello World!",
    publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
    subscribedChannel: "my_channel_1",
    subscription: null,
    timetoken: "14966804541029440"
}
```

#### Presence response

| Object | Description |
| --- | --- |
| `action` | Can be `join`, `leave`, `state-change` or `timeout`. |
| `channel` | The `channel` for which the message belongs. |
| `occupancy` | No. of users connected with the `channel`. |
| `state` | User State. |
| `subscription` | The `channel group` or wildcard subscription match (if exists) |
| `timestamp` | Current `timetoken`. |
| `timetoken` | Publish `timetoken`. |
| `uuid` | UUIDs of users who are connected with the `channel`. |

```json
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
```

### Other examples

#### Subscribing to multiple channels

It's possible to subscribe to more than one channel using the [Multiplexing](https://www.pubnub.com/docs/general/channels/subscribe#channel-multiplexing) feature. The example shows how to do that using an array to specify the channel names.

:::note Alternative subscription methods
You can also use [Wildcard Subscribe](https://www.pubnub.com/docs/general/channels/subscribe#wildcard-subscribe) and [Channel Groups](https://www.pubnub.com/docs/general/channels/subscribe#channel-groups) to subscribe to multiple channels at a time. To use these features, the *Stream Controller* add-on must be enabled on your keyset in the [Admin Portal](https://admin.pubnub.com).
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
    channels: ['my_channel_1', 'my_channel_2', 'my_channel_3']
});
```

#### Subscribing to a Presence channel

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/).
:::

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending `-pnpres` to the channel name. For example the channel named `my_channel` would have the presence channel named `my_channel-pnpres`.

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

const pubnub = PubNubVue.getInstance();

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

#### Sample Responses

#### Join event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "join",
    "timetoken": "15119466699655811",
    "occupancy": 2,
    "uuid": "User1",
    "timestamp": 1511946669
}
```

#### Leave event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "leave",
    "timetoken": "15119446002445794",
    "occupancy": 1,
    "uuid": "User1",
    "timestamp": 1511944600
}
```

#### Timeout event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "timeout",
    "timetoken": "15119519897494311",
    "occupancy": 3,
    "uuid": "User2",
    "timestamp": 1511951989
}
```

#### State change event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "state-change",
    "state": {
        "isTyping": true
    },
    "timetoken": "15119477895378127",
    "occupancy": 5,
    "uuid": "User4",
    "timestamp": 1511947789
}
```

#### Interval event

```json
{
    "action": "interval",
    "occupancy": 2,
    "timestamp": 1511947739
}
```

When a channel is in interval mode with `presence_deltas` `pnconfig` flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

* joined
* left
* timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

```json
{
    "action":"interval",
    "timestamp":1548340678,
    "occupancy":2,
    "join":["pn-94bea6d1-2a9e-48d8-9758-f1b7162631ed","pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"]},
    "timedout":["pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"],
    "b":"my-channel-pnpres"
}
```

If the full interval message is greater than `30KB` (since the max publish payload is `∼32KB`), none of the extra fields will be present. Instead there will be a `here_now_refresh` boolean field set to `true`. This indicates to the user that they should do a `hereNow` request to get the complete list of users present in the channel.

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "interval",
    "timetoken": "15119477396210903",
    "occupancy": 4,
    "timestamp": 1511947739,
    "here_now_refresh" : true
}
```

#### Wildcard subscribe to channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/) (with Enable Wildcard Subscribe checked). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to `a.*` you will get all messages for `a.b`, `a.c`, `a.x`. The wildcarded `*` portion refers to any portion of the channel string name after the `dot (.)`.

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

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
    channels: ['ab.*']
});
```

:::note Wildcard grants and revokes
Only one level (`a.*`) of wildcarding is supported. If you grant on `*` or `a.b.*`, the grant will treat `*` or `a.b.*` as a single channel named either `*` or `a.b.*`. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like `a.*`.
:::

#### Subscribing with state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/).
:::

:::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 PubNubVue from 'pubnub-vue';

const pubnub = PubNubVue.getInstance();

pubnub.addListener({
    status: function(statusEvent) {
        if(statusEvent.category === "PNConnectedCategory") {
            varnewState = {
                new: 'state'
            };
            pubnub.setState(
                {
                    state: newState
                },
                function(status) {
                    // handle state setting response
                }
            );
        }
    },
    message: function(message) {
        // handle message
    },
    presence: function(presenceEvent) {
        // handle presence
    }
});

pubnub.subscribe({
    channels: ['ch1', 'ch2', 'ch3']
});
```

#### Subscribe to a channel group

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
    channelGroups: ['my_channelGroup']
});
```

#### Subscribe to the Presence channel of a channel group

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
    channelGroups: ['family'],
    withPresence: true
});
```

#### Subscribing to multiple channel groups

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
    channelGroups: ['my_channelGroup1', 'my_channelGroup2', 'my_channelGroup3']
});
```

#### Subscribing to a channel and channel group simultaneously

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.subscribe({
    channels: ['my_channel'],
    channelGroups: ['my_channelGroup']
});
```

## Unsubscribe

When subscribed to a single channel, this function causes the client to issue a `leave` from the `channel` and close any open socket to the PubNub Network. For multiplexed channels, the specified `channel`(s) will be removed and the socket remains open until there are no more channels remaining in the list.

:::warning
**Unsubscribing** from all channels, and then **subscribing** to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received `timetoken` and thus, there could be some gaps in the subscription that may lead to message loss.
:::

### Method(s)

To `Unsubscribe from a channel` you can use the following method(s) in the Vue SDK:

```javascript
unsubscribe({Array channels, Array channelGroups})
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | Specifies the `channel` to unsubscribe from. |
| `channelGroups`Type: Array | Specifies the `channelGroups` to unsubscribe from. |

### Sample code

Unsubscribe from a channel:

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

const pubnub = PubNubVue.getInstance();

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

### Response

The output below demonstrates the response to a successful call:

```json
{
    "action" : "leave"
}
```

### Other examples

#### Unsubscribing from multiple channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.unsubscribe({
    channels: ['chan1', 'chan2', 'chan3']
});
```

**Example Response:**

```json
{
    "action" : "leave"
}
```

#### Unsubscribing from multiple channel groups

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

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

const pubnub = PubNubVue.getInstance();

pubnub.unsubscribe({
    channelGroups : ['demo_group1', 'demo_group2']
});
```

## Unsubscribe all

Unsubscribe from all channels and all channel groups

### Method(s)

```javascript
unsubscribeAll()
```

### Sample code

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

const pubnub = PubNubVue.getInstance();

pubnub.unsubscribeAll();
```

### Returns

None

## Listeners

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

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

## Terms in this document

* **Channel** - A pathway for sending and receiving messages between devices, created automatically when you first use it, that can handle any number of users and messages for different communication needs, like 1-1 text chats, group conversations, and other data streaming.
* **Channel pattern** - A way to group and analyze channel data to track performance metrics like message counts and user engagement over time with PubNub Insights.
