Home > Software design >  Vue.js return component value to vanilla javascript
Vue.js return component value to vanilla javascript

Time:11-21

I'm wondering if I am able to get a components data, the count property in this instance and console.log it into normal javascript, is this possible? I'm wanting to do console.log(btn.data.count) in this case

 <div id="app" v-cloak>
        <h1>{{greeting}}</h1>

        <button-counter></button-counter>
    </div>
    <script src="https://unpkg.com/vue@next"></script>

    <script>


        let app = Vue.createApp({
            data: function(){
                return {
                  greeting: "hi"
                }
            }
        })

        let btn = app.component('button-counter', {
            data: function () {
                return {
                    count: 0
                }
            },
            template: '<button v-on:click="count  ">You clicked me {{ count }} times.</button>'
        })
        console.log(btn.data.count) // doesn't work
        app.mount("#app")
    </script>

CodePudding user response:

There might be multiple instances of the button-counter component, so you cannot ask for the count.

You can only access the data from within the component itself. For example from within a method that handles the click event:

        let btn = app.component('button-counter', {
            data: function () {
                return {
                    count: 0
                }
            },
            methods: {
              onClick() {
                console.log(this.count)
                this.count  
              }
            },
            template: '<button v-on:click="onClick">You clicked me {{ count }} times.</button>'
        })

CodePudding user response:

You can use console.log normally you just need to use it where it makes sense. It does not make sense using it before #app is mounted.

Try writing a method for your count and add console log there you will see that it gets executed every time.

  • Related