Vue2.x之组件使用注意点

本文介绍了Vue.js中组件的正确使用方式,包括利用is属性解决DOM结构问题、子组件data属性的定义方法以及ref属性的使用技巧。通过具体实例展示了如何在Vue应用中实现计数器组件间的互动及数据同步。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>组件使用注意点</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="root">
    <table>
        <tbody>
            //使用is解决bug
            <tr is="row"></tr>
            <tr is="row"></tr>
            <tr is="row"></tr>
        </tbody>
    </table>
</div>
<script>
    Vue.component('row',{
        template:'<tr><td>this is a row</td></tr>'
    });
    let vm = new Vue({
        el:'#root'
    })
</script>
</body>
</html>
  1. 使用is作为html5规范的践行
  2. 子组件中的data必须是函数,并且要有返回值。在根组件data可以为对象
  3. ref的使用:在标签上使用获得的是dom元素,在组件上使用获取的是组件本身
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>counter</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="root">
    <counter ref='one' @change="handleCounterClick"></counter>
    <counter ref='two' @change="handleCounterClick"></counter>
    <div>{{ total }}</div>
</div>
<script>
    Vue.component('counter', {
        template: '<div @click="handleClick">{{ number }}</span>',
        data() {
            return {
                number: 0
            }
        },
        methods: {
            handleClick: function () {
                this.number++;
                this.$emit('change')
            }
        }
    });
    let vm = new Vue({
        el: '#root',
        data: {
            total: 0
        },
        methods: {
            handleCounterClick: function () {
                this.total = this.$refs.one.number + this.$refs.two.number
            }
        }
    })
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值