账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Vue 如何在 data 中使用 this 绑定 methods 中的方法?
    30
    0

    Vue 如何在 data 中使用 this 绑定 methods 中的方法?

    场景

    吾辈需要在 data 块中绑定 methods 的函数,有什么方法可以做到么?

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
      </head>
      <body>
        <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js"></script>
        <script>
          class Table extends Vue {
            constructor({ data, methods, mounted }) {
              super({
                data,
                methods,
                mounted,
              })
            }
          }
    
          const table = new Table({
            data: {
              user: {
                birthday: new Date(),
                birthdayFormatter: this.calcTime,
              },
            },
            methods: {
              calcTime(time) {
                console.log(time, this)
              },
            },
          })
          console.log(table.$data.user.birthdayFormatter)
        </script>
      </body>
    </html>

    现在打印的结果是 undefined,说明 thisdata 中就已经被认为是 window 对象了


    吾辈将之放到了计算属性中,仍然是没有效果的。
    这个问题的本质在于如何在传值的过程中为某个作用域的 this 绑定为 vue 实例本身,而在绑定的时候 vue 实例并未完成创建

    class Table extends Vue {
        constructor({ data, methods, mounted, computed }) {
          super({
            data,
            methods,
            mounted,
            computed,
          })
        }
    }
    
    const table = new Table({
        methods: {
          calcTime(time) {
            return time.toISOString()
          },
        },
        computed: {
          user: () => ({
            birthday: new Date(),
            birthdayFormatter: this.calcTime,
          }),
        },
    })
    console.log(table.user.birthdayFormatter)
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 叶渊晦 普通会员 1楼

      在 Vue 中,你可以使用 this 关键字来绑定 methods 中的方法。this 关键字在函数内部是表示函数作用域的。在 Vue 中,每个组件都有一个独立的作用域,而 methods 是组件内部的方法。

      以下是一个简单的例子:

      ```javascript // 我们创建一个组件,该组件有一个方法 var MyComponent = { data() { return { myMethod: function() { console.log('This is my method from the component'); } }; } };

      // 在模板中,我们使用 this 关键字来调用方法

      ```

      在这个例子中,我们首先定义了一个组件 MyComponent,它有一个名为 myMethod 的方法。然后在模板中,我们使用 @click 注解来触发方法。

      当我们点击这个按钮时,myMethod 方法会被调用。在调用方法时,this 的值是组件,也就是 MyComponent。因此,myMethod 方法会打印出 "This is my method from the component"。

      注意,这种方法可以让你在组件的任何地方调用方法,而不仅仅是 this。只要你正确地使用 this,就可以在任何地方调用方法。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部