chaihongjun.me

【Vue】关于Vue自定义组件事件监听和属性绑定的注意事项

【Vue】关于Vue自定义组件事件监听和属性绑定的注意事项

最近学习Vue.js,发现一个问题:

   <div id="app">
        <p>数字: {{number}}</p>
        <button @click="plusOne(rand1,$event)">点一下加2</button>
        <customize-btn :class="btnClass"></customize-btn>
    </div>
    <script type="text/javascript">
    var rand1=Math.random()*10;
    var rand2=Math.random()*10;
    var customizeBtn = {
        data: function() {
            return { btnClass: "btn" }
        },
        template: ` <div @click.native="minus(rand2)" >这是一个自定义的组件,让它拥有点击事件能力,就像个按钮</div>  `,
    }
    var app = new Vue({
        el: "#app",
        data: {
            message: 'hello world',
            number: 3,
            rand1:rand1,
            rand2:rand2
        },
        methods: {
            plusOne: function(num, a) {
               console.log(rand1);
                this.number = this.number + num;
                console.log("随机增加一个数后的:" + this.number);
                this.rand1=Math.random()*10;
                return this.number;
            },
            minus: function(num) {
                console.log(rand2);
                this.number = this.number - num;
                console.log("随机减去一个数后的:" + this.number);
                 this.rand2=Math.random()*10;
                return this.number;
            }
        },
        components: {
            "customizeBtn": customizeBtn
        }
    })
    </script>

发现下面几个情况:


1.事件监听和样式属性绑定都直接写在组件标签上

<customize-btn  @click.native="minus(rand2)" :class="btnClass" ></customize-btn>

报错btnClass未定义


2.事件监听和样式属性绑定都直接写在tempalet里面

template: ` <div  @click.native="minus(rand2)" :class="btnClass">这是一个自定义的组件,让它拥有点击事件能力,就像个按钮</div>  `,

不报错,但是第二个按钮点击无效,事件没绑上


3.事件监听写在template,样式属性绑定写在组件标签上

<customize-btn  :class="btnClass" ></customize-btn>
<!--  ...中间其他代码 -->
template: ` <div  @click.native="minus(rand2)">这是一个自定义的组件,让它拥有点击事件能力,就像个按钮</div>  `,

报错,btnClass未定义


4.第三种就是最前面的那样。事件监听写在组件标签上,样式属性绑定写在template里,这里正常。

<customize-btn  @click.native="minus(rand2)"></customize-btn>
template: ` <div :class="btnClass">这是一个自定义的组件,让它拥有点击事件能力,就像个按钮</div>  `,


从结论看,自定义组件的事件监听必须写在组件标签上,而自定义组件的样式属性(包括其他属性?)绑定必须在template里面? 这个结论对不对呢?为什么呢?


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:柴宏俊»