vue 中this的指向问题

场景:一个<component></component>里边is的值有三种:Home,Login,reg
Home组件中有a标签,点击跳转到Login,我希望能实现组件的切换效果。该如何实现?
一下是示例代码,我用的是自定义函数,希望能够从子组件改变父组件的 currentView ,可惜pfun中的this指向却是vue$3,麻烦帮忙解答,感谢。

点击查看示例

代码如下:

    <h4>动态组件</h4>
    <div id="app">
      <component v-on:jump="pfun" v-bind:is="currentView"></component>
    </div>

    <script>

    var Home = {
      props:['curr'],
      template:'<div>\
        Home\
        <p><a v-on:click="cfun">登陆</a></p>\
      </div>',
      methods:{
        cfun:function() {
          this.$emit('jump', 'Login');
        }
      }
    };

    var Login = {
      template:'<div>Login</div>'
    };

    var Reg = {
      template:'<div>Reg</div>'
    };

    var app = new Vue({
      el: '#app',
      data:{
        currentView:Home
      },
      methods:{
        pfun:function(path) {
          this.currentView = path;//这里想切换组件的显示该怎么做 ?
        }
      }
    });
阅读 11.3k
2 个回答

使用bind函数改变this的指向,也可以使用es6的箭头函数
之前的答案应该是错误的

注意,不应该使用箭头函数来定义 method 函数 (例如 plus: () => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined。

官方文档里已经说过了,this应该是已经处理过的;这里你的this并没有错误,也不是this的问题。
主要问题是组件没有注册,data里面的Home应该加引号。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题