Vue起步_使用组件化思想修改TodoList

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <!-- <script src="/assets/js/vue.js"></script> -->
    <script src="E:\Code\Vue\assets\js\vue.js"></script>
</head>

<body>
   <div id="app">
       <input type="text" v-model="inputValue"/>
       <button v-on:click="handleBtnClick">提交</button>
       <ul>
           <li v-for="item in list">{{item}}</li>
       </ul>
   </div>

   <script>
       var app = new Vue({
           el: '#app',
           data: {
               list: [],
               inputValue: ''
           },
           methods: {
            handleBtnClick: function(){
               this.list.push(this.inputValue)
               this.inputValue = ''
            }
           }
       })
   </script>
</body>

</html>

把<li>标签的内容整体变为组件:

<body>
   <div id="app">
       <input type="text" v-model="inputValue"/>
       <button v-on:click="handleBtnClick">提交</button>
       <ul>
           <!-- <li v-for="item in list">{{item}}</li> -->
           <todo-item v-for="item in list"></todo-item>
       </ul>
   </div>

   <script>

       Vue.component("TodoItem", {
           template: "<li>todo item</li>"
       })

       var app = new Vue({
           el: '#app',
           data: {
               list: [],
               inputValue: ''
           },
           methods: {
            handleBtnClick: function(){
               this.list.push(this.inputValue)
               this.inputValue = ''
            }
           }
       })
   </script>
</body>


v-bind指令:

向子组件传入一个绑定值

使用全局组件

通过content字段传值,子组件中通过props:  ['content']接收值。

<body>
    <div id="app">
        <input type="text" v-model="inputValue" />
        <button v-on:click="handleBtnClick">提交</button>
        <ul>
            <todo-item v-bind:content="item" v-for="item in list"></todo-item>
        </ul>
    </div>

    <script>

        Vue.component("TodoItem", {
            props: ['content'],
            template: "<li>{{content}}</li>"
        })

        var app = new Vue({
            el: '#app',
            data: {
                list: [],
                inputValue: ''
            },
            methods: {
                handleBtnClick: function () {
                    this.list.push(this.inputValue)
                    this.inputValue = ''
                }
            }
        })
    </script>
</body>

局部组件

var TodoItem = {
props: [ 'content'],
template: "<li>{{content}}<li>"
}

将局部组件注册到根Vue实例里(通过对象的方式):

var app = new Vue({
el: '#app',
components: {
TodoItem: TodoItem
},
data: {
list: [],
inputValue: ''
},
methods: {
handleBtnClick : function () {
this. list. push( this. inputValue)
this. inputValue = ''
}
}
})


猜你喜欢

转载自blog.csdn.net/qq_17832583/article/details/80393469