- 效果(輸入資料,點選按鈕送出。點選資料可删除)
- 父-子:父元件通過
綁定資料,子元件props接收資料v-band
- 子-父:子元件通過
觸發父元件的自定義事件并且傳遞資料,父元件通過監聽事件接收。$emit
-
代碼
(本地引用了vue.js)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父子元件之間傳值</title>
<script src="vue.js"></script>
<style>
li{cursor:pointer;}
</style>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue">
<button @click="handleBtnClick">按鈕</button>
<ul>
<todo-item :content="item"
:index="index"
v-for="(item, index) of list" :key="index"
@delete = 'handleItemDelete'>
<!--監聽delete事件-->
</todo-item>
</ul>
</div>
<script>
var TodoItem = {
//子元件接收父元件傳遞來的資料
props: ['content','index'],
template: '<li @click="handleItemClick">{{content}}</li>',
methods: {
handleItemClick: function () {
//$emit子元件觸發父元件的自定義事件(delete),并且傳遞資料(index)
this.$emit('delete',this.index)
}
}
}
var app = new Vue({
el: '#app',
components:{
TodoItem
},
data: {
list: [],
inputValue: ''
},
methods: {
handleBtnClick: function () {
this.list.push(this.inputValue)
this.inputValue = ''
},
handleItemDelete: function (index) {
this.list.splice(index,1)
}
}
})
</script>
</body>
</html>
-
上一篇部落格
簡單的vue編寫TodoList(未使用元件)
如有錯誤,望各位大佬指正。