【问题标题】:Incorrect component scope inside a $route watch function on VueJsVueJs 上 $route 监视函数中的组件范围不正确
【发布时间】:2018-02-08 16:34:40
【问题描述】:

全部。

我正在开发一个需要根据应用路由路径加载/更改数据的应用。

要知道 url 何时更改,我在 $route 中添加了一个 watch 函数,并且我想在同一个组件中调用一个函数来加载数据,所有工作都只是 @ 的范围watch 函数内的 987654323@ 而不是引用 VueComponent 实例正在返回另一个对象。

这是我的简化代码

组件.vue

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

这是我在watch 函数中为this 获得的对象

{default: {…}, __esModule: true}
default : beforeCreate : [ƒ]
beforeDestroy : [ƒ]
created : ƒ created()
data : ƒ data()
name : "lists"
render : ƒ ()
staticRenderFns : []
watch : {$route: ƒ}
_Ctor : {0: ƒ}
__file : "../my-app/src/components/Lists.vue"
__proto__ : Object

不确定这种方法是否正确或我缺少什么。

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

    标签: vuejs2 vue-component vue-router


    【解决方案1】:

    不要使用箭头函数来定义监视处理程序(或方法、计算值或生命周期方法等)。箭头函数在词法上绑定this,并且不能重新绑定。

    相反,只需使用常规函数即可。 Vue 会将其绑定到 Vue。

    watch:{
      $route: function(value){
        console.log('ROUTE CHANGED');
        console.log(value); /* Route Object */
        console.log(this); /* NOT A VueComponent */
        this.pageTitle = 'Some new title';
      }
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 2016-08-28
      • 1970-01-01
      • 2015-02-04
      相关资源
      最近更新 更多