Incorrect component scope inside a $route watch function on VueJs

时间:2017-08-30 20:34:23

标签: vuejs2 vue-component vue-router

all.

I'm working on an app where I need to load/change data according to the app route path.

To know when the url has been changed I've added a .modalBox function to the .modalBox { //modalBox styles &#{&} { margin: 0 auto; position: absolute; background-color: $brand-dark; left: calc(50% - (#{$modalBox-width} / 2)); top: calc(50% - (#{$modalBox-height / 2} + #{$modalBox-padding-bottom / 2})); width: $modalBox-width; height: $modalBox-height; text-align: center; align-items: center; padding: $modalBox-padding-top $modalBox-padding-left-right $modalBox-padding-bottom; } //Inner main modalBox div &--inner { position: absolute; bottom: 0; padding: 0 em(50) em(25); left: 0; } } and I want to call a function in the same component to load data, all works the only thing is the scope of @media screen and (max-width: em(602)) { .modalBox { width: 90%; } } inside the watch function instead of referred to the VueComponent instance is returning another object.

Here is my simplified code to get an idea

component.vue

$route

This is the object I get for this inside the watch function

<template>
  <div id="lists">
    {{pageTitle}}
  </div>
</template>

<script>
  export default {
    name: 'lists',
    data() {
      return {
        pageTitle: 'Some Title',
      };
    },
    created() {
      console.log('LOAD THE ASKED PATH');
      console.log(this.$route.params); /* Object */
      console.log(this); /* VueComponent Instance */
    },
    watch: {
      $route: (value) => {
        console.log('ROUTE CHANGED');
        console.log(value); /* Route Object */
        console.log(this); /* NOT A VueComponent */
        this.pageTitle = 'Some new title';
      },
    },
  };
</script>

Not sure if this approach is correct or what I'm missing.

Any help will be appreciated.

Thanks in advance.

1 个答案:

答案 0 :(得分:1)

Don't use arrow functions to define watch handlers (or methods, or computed values, or lifecycle methods, etc). Arrow functions bind blog.html lexically, and they cannot be re-bound.

Instead, just use a regular function. Vue will bind it to the Vue.

public static void main(String[] args) {

    JFileChooser fileChooser = new JFileChooser(".");
    int status = fileChooser.showOpenDialog(null);

    if (status == JFileChooser.APPROVE_OPTION) {
      File selectedFile = fileChooser.getSelectedFile();
      System.out.println(selectedFile.getParent());
      System.out.println(selectedFile.getName());
    } else if (status == JFileChooser.CANCEL_OPTION) {
      System.out.println("canceled");
    }

}