C
C
cihone81222021-02-24 09:28:55
JavaScript
cihone8122, 2021-02-24 09:28:55

vue3. How to access a function from a directive?

Code example:

<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="app">
  <button v-test>click me</button>
</div>

<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<script>
(function () {
  'use strict';

  const App = {};

  const TestDirective = {
    data() {
      return {
        someData: [123, 456]
      }
    },
    methods: {
      helloMethod() {
        console.log('hello from method!');
      }
    },
    mounted() {
      // ↓↓↓ Вот тут появляется ошибка "Uncaught TypeError: Cannot read property 'helloMethod' of undefined"
      this.helloMethod()
      // ↑↑↑

      console.log(this.someData);
    }
  };

  const app = Vue.createApp(App);
  app.directive('test', TestDirective);
  app.mount('#app');
})();
</script>
</body>
</html>


When running this code, an error is displayed in the console:
Uncaught TypeError: Cannot read property 'helloMethod' of undefined

The reason seems to be understood - the this variable is undefined.
But then how do you access the helloMethod function and the local variable someData ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
profesor08, 2021-02-24
@cihone8122

Read carefully here https://v3.vuejs.org/guide/custom-directive.html , pay special attention to working with arguments.

B
black1277, 2021-02-24
@black1277

instead of this.helloMethod() you need to write this.methods.helloMethod()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question