01慕课网《vue.js2.5入门》——Vue中的组件

TodoList功能开发

例子:输入字符,在列表中显示

<body>
<div id="root">
    <div>
        <input v-model="inputValue"/>
        <button @click="handleSubmit">提交</button>
        <ul>
            <li v-for="(item,index) of list" :key="index">
                {{item}}
            </li>
        </ul>
    </div>
</div>
<script>
    // vue实例
    new Vue({
        el: "#root",
        data: {
            inputValue: '',
            list: []
        },
        methods: {
            handleSubmit: function () {
                this.list.push(this.inputValue);
                this.inputValue = '';
            }
        }
    })
</script>
</body>

    

TodoList中组件拆分

组件:页面上的某一部分,将大型网页拆分成几个部分

定义组件:

全局:Vue.component('todo-list(组件名称)',{   });只用组件<todo-list></todo-list>

局部:定义+声明componts

组件之间的通信:

 例子:将<li>标签拆成一个组件

<body>
<div id="root">
    <div>
        <input v-model="inputValue"/>
        <button @click="handleSubmit">提交</button>
        <ul>
            <!--使用全局组件-->
            <todo-itemfull v-for="(item,index) of list" :key="index" :content="item"></todo-itemfull>

        </ul>
        <ul>
            <!--使用局部组件-->
            <todo-itemonly></todo-itemonly>

        </ul>
    </div>
</div>
<script>
    // 定义全局组件
    Vue.component('todo-itemfull', {
        // 接受名为content的属性
        props:['content'],
        // 组件模板
        template: '<li>{{content}}</li>'
    });
    // 定义局部组件
    var TodoItem = {
        template: '<li>局部组件</li>'
    }
    // vue实例
    new Vue({
        el: "#root",
        data: {
            inputValue: '',
            list: []
        },
        // 声明局部组件
        components: {
            'todo-itemonly': TodoItem
        },
        methods: {
            handleSubmit: function () {
                this.list.push(this.inputValue);
                this.inputValue = '';
            }
        }
    })
</script>

猜你喜欢

转载自www.cnblogs.com/-beauTiFul/p/9032077.html