简体   繁体   English

Vue.js 返回组件值到 vanilla javascript

[英]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?我想知道我是否能够获取组件数据、此实例中的count属性并将其控制台记录到正常的 javascript 中,这可能吗? I'm wanting to do console.log(btn.data.count) in this case在这种情况下,我想做console.log(btn.data.count)

 <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 . button-counter组件可能有多个实例,因此您不能要求count

You can only access the data from within the component itself.您只能从组件本身访问数据。 For example from within a method that handles the click event:例如在处理click事件的方法中:

        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.你可以正常使用console.log,你只需要在有意义的地方使用它。 It does not make sense using it before #app is mounted.在安装#app之前使用它没有意义。

Try writing a method for your count++ and add console log there you will see that it gets executed every time.尝试为您的count++编写一个方法并在那里添加控制台日志,您将看到它每次都被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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