父组件 子组件之间传值
父->子
- 父组件 v-bind绑定属性
- 子组件 prop接收属性
子->父
- 子组件发送 emit 并传参
- 父组件@监听
ps:
子组件不能直接修改父组件传来的值 (比如下面的代码里handleItemClick函数里,不能够写this.index = 0;
<!--
父子组件传值
20190819
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id='app'>
<input type="text" v-model='todoValue'>
<button @click='handleButtonClick'>submit</button>
<ul>
<todo-item
v-bind:content='item'
v-bind:index='index'
v-for="(item, index) in list"
@delete="handleItemDelete"> <!--父组件监听子组件的delete事件 -->
</todo-item>
</ul>
</div>
</body>
<script src="./js/vue.min.js"></script>
<script>
// Vue.component("TodoItem",{
// props:['content'],
// template:"<li> {{content}} </li>"
// });
var TodoItem ={
props:['content', 'index'], //子组件接收父组件的属性值,父组件中使用v-bind
/*
//props可指定类型
props:{
content:String,
index:Number
},
*/
template:"<li @click='handleItemClick'> {{content}} </li>",
methods:{
handleItemClick:function()
{
this.$emit('delete', this.index);//子组件向父组件发送delete事件
}
}
};
var app = new Vue({
el: '#app',
data: {
todoValue: "",
list: []
},
components:{
TodoItem:TodoItem
},
methods:{
handleButtonClick:function()
{
this.list.push(this.todoValue);
this.todoValue = '';
},
handleItemDelete:function(index){
console.log(index);
this.list.splice(index, 1);
}
}
});
</script>
</html>
非父子之间传值
<!--
非父子组件传值 使用Vue.prototype 主线传值与监听
20190819
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id='app'>
<child content='one' ></child>
<child content='two' ></child>
</div>
</body>
<script src="./js/vue.min.js"></script>
<script>
//定义Vue的属性 ,所有vue示例均有此属性bus
Vue.prototype.bus = new Vue();
Vue.component('child',{
template:"<div @click='handlerClick'>{{selfcontent}}</div>",
props:{
content:{
type:String,
value:'default'
}
},
data: function(){
return {
selfcontent : this.content
}
},
methods:{
handlerClick: function(){
this.bus.$emit('change', this.selfcontent)
}
},
mounted: function(){
var this_ = this;
this_.bus.$on('change', function(msg){
console.log('change: '+msg)
this_.selfcontent = msg
})
}
});
var vm = new Vue({
el:'#app'
})
</script>
</html>