1. 程式人生 > >Vue元件學習

Vue元件學習

1.元件是指頁面上的某一部分,當建立一個大型的專案時,專案可以被分為很多元件,維護時就變的簡單多了。
2.Vue元件分為全域性元件和區域性元件,區域性元件需在例項中宣告(註冊)。
全域性元件宣告簡例:

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

區域性元件宣告簡例:

//宣告一個變數等於一個物件,物件裡面給一個模板
        var TodoItem={
            template:'<li>item</li>'
} new Vue({ el:"#root", components:{ 'todo-item':TodoItem } //如不在父元件中註冊區域性元件不可以使用

3.元件與例項的關係:每一個元件都是一個Vue例項,反過來每一個Vue例項也可以稱為一個元件,根例項的模板是掛載點裡的所有內容

4.Vue元件之間通訊方式:父元件通過屬性的形式向子元件傳值;

<body>
    <div id="root">
       <input
v-model="inputValue">
<button @click="handleSubmit">提交</button> <ul> <!-- <li v-for="(item,index) of list" :key="index">{{item}}</li> --> <todo-item v-for="(item,index) of list" :key="index" :content="item"></todo-item> </ul
>
</div> <script> Vue.component('todo-item',{ props:['content'],//props屬性值可以是一個數組,用於接收外部屬性 template:'<li>{{content}}</li>'//使用插值表示式顯示content }) new Vue({ el:"#root", data: { inputValue:'', list: [] }, methods:{ handleSubmit:function(){ this.list.push(this.inputValue) this.inputValue='' } } }) </script> </body> 這段程式碼實現了一個簡單的todolist功能,即在表單中輸入內容點選提交顯示在無序列表中; 子元件通過釋出訂閱模式來與父元件通訊:emit()方法; ``` this.$emit('delete',this.index)
 <ul>
       <todo-item v-for="(item,index) of list" :key="index" :content="item"
        :index="index" v-on:delete="handleDelete"></todo-item>
       </ul>
handleDelete:function(index){    //宣告一個形參用於接收實參
                    this.list.splice(index,1)     
                }

這段程式碼通過emit()方法實現了當點選當前列表項時就將當前列表項刪除。