今天學(xué)習(xí)了Vue組件中的非父子之間的傳值和生命周期
Vue組件之間的傳值分三種
1.父?jìng)髯又g傳值用屬性:props
2.子傳父之間傳值用方法:自定義方法
3.非父子之間傳值用第三方唆姐。
非父子之間傳值實(shí)例
<body>
<div id="demo">
<first></first>
<second></second>
</div>
<script src="js/vue.js"></script>
<script>
var bus=new Vue();
Vue.component('first',{
template:`
<div>
<h2>4987489789<h2>
<button @click='btn'>點(diǎn)擊</button>
</div>
`,
data:function(){
return{
msg:'hellow word'
}
},
methods:{
btn:function(){
bus.$emit('send',this.msg)
}
}
})
Vue.component('second',{
template:`
<div>
<h2>sdafsdfs</h2>
<a href="">{{mess}}</a>
</div>
`,
data:function(){
return{
mess:''
}
},
mounted:function(){
bus.$on('send',msg=>{
this.mess=msg
})
}
})
new Vue({
el:'#demo'
})
</script>
</body>
生命周期
20170303180741807.png
20170303180741807.png
生命周期分8個(gè)階段
1.beforeCreate(創(chuàng)建前)
2.created(創(chuàng)建后)
3.beforeMount(載入前)
4.mounted(載入后)
5.beforeUpdate(更新前)
6.updated(更新后)
7.beforeDestroy(銷毀前)
8.destroyed(銷毀后)
實(shí)例
<body>
<div id='app'>{{msg}}</div>
<script src='js/vue.js'></script>
<script>
new Vue({
el:'#app',
data:{
msg:'hello vue'
},
beforeCreate:function(){
alert('beforeCreated');
},
created:function(){
alert('created')
},
beforeMount:function(){
alert('beforMount')
},
mounted:function(){
alert('mounted')
}
})
</script>
</body>
作業(yè)(昨天)
父子組件通信
<body>
<div id="demo">
<lzy></lzy>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component('lzy',{
template:`
<div>
<ul>
<li v-for='(value,index) in arr'>{{value}}</li>
</ul>
<cont @send='newBtn' addName='jake'></cont>
<cont @send='newBtn' addName='jan'></cont>
</div>
`,
data:function(){
return{
arr:[]
}
},
methods:{
newBtn:function(txt){
this.arr.push(txt)
}
}
})
Vue.component('cont',{
props:['addName'],
template:`
<div>
<label>{{addName}}</label>
<input type="text" v-model='add'>
<button @click='btn'>點(diǎn)擊</button>
</div>
`,
data:function(){
return{
add:''
}
},
methods:{
btn:function(){
this.$emit('send',this.addName+':'+this.add)
}
}
})
new Vue({
el:'#demo'
})
</script>
</body>