Vue2.x之组件使用注意点

<!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>

猜你喜欢

转载自blog.csdn.net/qq_33733970/article/details/80633271