vue ref small case

This small case is mainly to review the publish and subscribe model and the use of ref. The
purpose is to display two components on the page. When each component is clicked, add 1 to the calculator of the root component. The code is as follows:

<body>
    <div id="app">
        <div>
            Component1:<counter @add-one="handleChange" ref="one" onselectstart="return false"></counter>
        </div>
        <div>
            Component2:<counter @add-one="handleChange" ref="two" onselectstart="return false"></counter>
        </div>
        <div>total: {
    
    {
    
    total}}</div>
    </div>

    <script>
        Vue.component('counter', {
    
    
            data() {
    
    
                return {
    
    
                    times: 0
                }
            },
            template: '<span @click="handleSpanClick"> {
    
    {times}}</span>',
            methods: {
    
    
                handleSpanClick() {
    
    
                    this.times ++
                    this.$emit('add-one')
                }
            }
        })
        var vm = new Vue({
    
    
            el: '#app',
            data: {
    
    
                total: 0
            },
            methods: {
    
    
                handleChange() {
    
    
                    this.total = this.$refs.one.times + this.$refs.two.times
                }
            }
        });
    </script>
</body>

Insert picture description here
effect:
Insert picture description here
note:
We can't use the handleChangefunction as a calculated attribute. For example, the following code is wrong: it
Insert picture description here
Insert picture description here
will report an error:
Insert picture description here
why it will report an error? Because it is not available in calculated properties this.$refs.
We need to know two things:

  1. The calculated attributes are executed after the created phase and before mounted
  2. The item of $refs does not exist until mounted.

So avoid counting in calculated properties $refs, because there is no
vue document that also mentions this:
Insert picture description here

Guess you like

Origin blog.csdn.net/dyw3390199/article/details/112395132