vue 父子元件傳值
阿新 • • 發佈:2020-08-02
以下程式碼需要到vue官網下載vue.js引入方可執行 https://cn.vuejs.org/js/vue.js
一、父元件向子元件傳值:
父元件向子元件通過v-bind的形式來進行資料的傳遞,子元件通過props來接收(程式碼中黃色背景標識為父元件向子元件傳值核心程式碼)
二、子元件向父元件傳值
子元件向父元件傳值,通過$emit的方式向上一層觸發事件,子元件觸發的事件父元件通過監聽就能獲取到子元件帶出來的內容,實現
子元件向父元件傳值(程式碼中紫色背景標識為子元件向父元件傳值核心程式碼)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button v-on:click="handleClick">提交</button> <ul> <todo-item :content='item' //v-bind 簡寫 : :index='index' v-for="(item,index) in list" @delete = 'handleItemClick' //v-on 簡寫 @ > </todo-item> </ul> </div> <script> var TodoItem = { props:['content','index'], template:"<li @click='handleItemClick'>{{content}}</li>", methods:{ handleItemClick:function(){ this.$emit('delete',this.index) } } } var app = new Vue({ el: "#app", components:{ TodoItem }, data: { list:[], inputValue:"" }, methods:{ handleClick: function(){ this.list.push(this.inputValue); this.inputValue = "" console.log(this.inputValue) }, handleItemClick:function(index){ this.list.splice(index,1) console.log(index) } } }) </script> </body> </html>