Skip to content

$watch example doesn't work because it uses const #575

Closed
@skirtles-code

Description

@skirtles-code

This example appears at https://v3.vuejs.org/api/instance-methods.html#watch:

const unwatch = vm.$watch(
  'value',
  function() {
    doSomething()
    if (unwatch) {
      unwatch()
    }
  },
  { immediate: true }
)

The same example appears in the Vue 2 docs but it uses var instead of const.

Unfortunately, the example doesn't work with const, it throws an error:

ReferenceError: Cannot access 'unwatch' before initialization

I've put it in JSFiddle so you can try it yourself: https://jsfiddle.net/skirtle/14r7sjn8/

Using let is much the same.

I see two relatively simple ways to fix it.

Solution 1 - Change it to var:

var unwatch = vm.$watch(

Solution 2 - Use let but on a separate line:

let unwatch = null

unwatch = vm.$watch(

I'm happy to make the change but I would appreciate some guidance on which approach to take.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions