1. 程式人生 > >Vue起步_使用元件化思想修改TodoList

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 = '' } } })