1. 犀牛前端部落首页
  2. Vue.js去哪儿

Vue2.5开发去哪儿网-Vue.js基础组件化思想修改TodoList

这篇文章我们将使用组件化的思想来修改一下,之前实现的TodoList功能

全局化组件的实现方式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TodoList</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" v-model="inputTxt">
        <button @click="submitEvent">提交</button>
        <ul>
            <todo-item v-bind:content="list" v-for="list in todoList" ></todo-item><!--向子组件传递绑定值 -->
        </ul>
    </div>
    <script>
        //创建全局组件
        Vue.component('TodoItem',{
            props:['content'],//接受传递的值
            template:`<li>{{this.content}}</li>`
        })
        var app = new Vue({
            el: '#app',
            data:{
                inputTxt:'',
                todoList: []
            },
            methods:{
                submitEvent: function(){
                 this.todoList.push(this.inputTxt);
                 this.inputTxt = '';
                }
            }
        })
    </script>
</body>
</html>

我们还可以使用子组件的方式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TodoList</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" v-model="inputTxt">
        <button @click="submitEvent">提交</button>
        <ul>
            <todo-item v-bind:content="list" v-for="list in todoList" ></todo-item>
        </ul>
    </div>
    <script>
        //子组件
    let TodoItem = {
            props:['content'],
            template:`<li>{{this.content}}</li>`
        };
        var app = new Vue({
            el: '#app',
            data:{
                inputTxt:'',
                todoList: []
            },
            methods:{
                submitEvent: function(){
                 this.todoList.push(this.inputTxt);
                 this.inputTxt = '';
                }
            },
            components:{
                TodoItem: TodoItem
            }
        })
    </script>
</body>
</html>

 

原创文章,作者:犀牛前端部落,如若转载,请注明出处:https://www.pipipi.net/2727.html

发表评论

登录后才能评论