为什么组件自定义事件不能在写在模板里监听,而属性又不能写在组件上绑定?

 <div id="app">
        <p>数字: {{number}}</p>
        <button @click="plusOne(rand1,$event)">点一下加2</button>
        <customize-btn  @click.native="minus(rand2)"  ></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 :class="btnClass">这是一个自定义的组件,让它拥有点击事件能力,就像个按钮</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里面? 这个结论对不对呢?为什么呢?

阅读 2.1k
1 个回答

1.<customize-btn @click.native="minus(rand2)" :class="btnClass" ></customize-btn> 这是要将父组件的btnClass传递个子组件,但是父组件中没有btnClass,所以btnClass is undefined!同问题3
2.<div @click.native="minus(rand2)" :class="btnClass"> 子组件中没有定义minus的function
3.<customize-btn @click.native="minus(rand2)"></customize-btn> 建议你了解下父子组件的通信

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题