父组件:
子组件
例子01:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<!-- v-model实现双向绑定 -->
<!-- v-bind:可以将绑定的值传给子组件 (key,Vue) -->
<!-- @click 点击事件 -->
<input type="text" v-model="inputvalue" />
<button @click="handleBtnclick">提交</button>
<!-- @delete接受子组件传过来的值 handleItemdelete写在父组件的methods -->
<Todo-item v-bind:content="list" @delete="handleItemdelete"></Todo-item>
</div>
</body>
<script>
var TodoItem = {
props: ['content'],
template: "<ul><li v-for='(item,index) in content' @click='handleItemClick(index)'>{{item}}</li></ul>",
methods: {
handleItemClick(index) {
//绑定事件向父组件传值
this.$emit("delete",index);
}
}
}
var app = new Vue({
el: '#app',
data: {
list: ['第一课内容', '第二课内容'],
inputvalue: ''
},
methods: {
handleBtnclick() {
this.list.push(this.inputvalue);
this.inputvalue = '';
},
handleItemdelete(obj) {
//处理传过来的值
this.list.splice(obj,1);
}
},
components: {
TodoItem
}
})
</script>
</html>
例子02:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>父子组件之间的传值</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<counter ref="one" :count="0" @change="handlechange"></counter>
<counter ref="two" :count="0" @change="handlechange"></counter>
<div>{{total}}</div>
</div>
</body>
<script>
var counter = {
// vue是一个单项数据流, 子组件不能直接改变父组件传过来的值
props:['count'],
template:'<div @click="handleClik">{{num}}</div>',
// data: 与 data() 使用场景
// data: 用设置初始参数,不接受父组件传值的时候
// data()当接受父组件传值的时候使用
data(){
return{
num:this.count
}
},
methods:{
handleClik(){
this.num++;
this.$emit("change")
}
}
}
var vm = new Vue({
el:"#app",
data:{
total:0
},
components:{
counter:counter
},
methods:{
handlechange(){
this.total = this.$refs.one.num+this.$refs.two.num;
}
}
})
</script>
</html>
Vue原生省事件绑定
//通过子组件通知进行绑定click
<counter @clik="handleclick"></counter>
//不需要子组件this.$emit通知就可执行
<counter @clik.native="handleclick"></counter>