简体   繁体   中英

Vue.js return component value to vanilla javascript

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>

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>'
        })

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM