1. 父组件传值给子组件:v-bind:'atrName' = '来自父组件的数据' , props['atrName']定义在子组件中接收来自父组件中的数据
2.子组件传值给父组件:
方式一:(1)父组件中定义接收数据的对象数组名list,(2)子组件中定义需要传输的数据inputText,(3)子组件中定义方法用this.$parent.list.push['inputText'],即可将数据传递给list
方法二:父组件中使用子组件,并在子组件标签中添加属性并给属性赋值,(1)<son @toFather =‘recEvent’ >,(2)子组件中添加方法用this.$emit('toFather','来自子组件的数据'),(3)父组件中添加方法并且名字为recEvent= function(results){},resutls即为接收到的子组件数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue template</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="example">
<to-do-box></to-do-box>
</div>
<script type="text/x-template" id="box-template">
<div>
<to-do-input ></to-do-input>
<to-do-list :myList="list" @toBox="recEvent"></to-do-list>
</div>
</script>
<script type="text/x-template" id="input-template">
<div>
<p>待做事项列表:</p>
<input type="text" v-model="inputText">
<button @click="handleAdd">add</button>
</div>
</script>
<script type="text/x-template" id="list-template">
<ul>
<to-do-item v-for="temp in myList" :content="temp" @toList="recEvent"></to-do-item>
</ul>
</script>
<script type="text/x-template" id="item-template">
<li>
<button @click="handleDelete">delete</button>
<span>{{content}}</span>
</li>
</script>
<script type="text/javascript">
Vue.component('to-do-box',{
template:`#box-template`,
data:function(){
return {
list:[]
}
},
methods:{
recEvent:function(results){
console.log("data in box: " + results);
this.list.pop(results);
}
}
});
Vue.component('to-do-input',{
template:`#input-template`,
data:function(){
return {
inputText:''
}
},
methods:{
handleAdd:function(){
this.$parent.list.push(this.inputText);//使用$parent直接将v-model中的的值inputText传递给父组件的list数组
}
}
});
Vue.component('to-do-list',{
template:`#list-template`,
// 父组件传过来的值放在了绑定的属性变量myList中,myList的具体值为父组件的list数组
props:['myList'],
methods:{
recEvent:function(results){
console.log("recEvent in list:" + results);
this.$emit('toBox',results);
}
}
});
Vue.component('to-do-item',{
template:`#item-template`,
props:['content'],
methods:{
handleDelete:function(){
this.$emit('toList',this.content);
console.log("content in item: "+this.content);
}
}
});
new Vue({
el: "#example",
data: {
myValue: "test!"
}
}
);
</script>
</body>
</html>