1

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>
1
  • you should register you component inside components i guess Commented Nov 20, 2021 at 10:36

2 Answers 2

3

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>'
        })
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.