Vue2学习(4)vue组件生命周期+组件之间数据共享
Vue2学习(4)vue组件生命周期+组件之间数据共享
·
Vue组件的生命周期
生命周期(Life Cycle)是指一个组件从创建 -->运行 --> 销毁的整个阶段。
生命周期函数:是由 vue 框架提供的内置函数,会伴随着组件的生命周期,自动按次序执行。
(下面图片来自网络)
组件之间的数据共享
- 父组件向子组件共享数据(使用自定义属性即props)
//父组件--APP.vue
<template>
<div class="app-container">
<h1>App根组件 --- {{ countFromSon }}</h1>
<p>{{ userinfo }}</p>
<hr />
<div class="box">
<!-- 渲染 Left 组件-->
<Left :msg="message" :user="userinfo"></Left>
</div>
</div>
</template>
<script>
import Left from '@/components/Left.vue'
export default {
data() {
return {
message: 'GDUF-LoverMaker',
userinfo: { name: 'lizhi', age: 22 },
countFromSon: 0
}
},
components: {
Left
}
}
</script>
//子组件--Left.vue
<template>
<div class="left-container">
<h3>Left 组件</h3>
<p>msg 的值是:{{ msg }}</p>
<p>user 的值是:{{ user }}</p>
</div>
</template>
<script>
export default {
props: ['msg', 'user'],//自定义属性,父组件向子组件共享数据
}
</script>
-
子组件向父组件共享数据
子组件向父组件共享数据使用自定义事件。
$.emit(event,val)
//父组件APP.vue <template> <div id="app"> <p>父组件中的countFromSon: {{ countFromSon }}</p> //使用自定义事件,还要在父组件中定义函数即getCount函数 <First :msg="message" @numChange="getCount"></First> </div> </template> <script> import First from '@/components/First.vue' export default { data() { return { message: 'Best wishes!', countFromSon: 0 } }, components: { // HelloWorld, First }, methods: { //定义方法接受子组件的count值 getCount(val){ this.countFromSon = val } } } </script> <style lang="less"> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; // text-align: center; color: #2c3e50; margin-top: 60px; } </style>
//子组件First.vue <template> <div> <h5>子组件</h5> <p>父组件传递过来的值:{{ msg }}</p> <hr> <p>子组件中的count: {{ count }}</p> <button @click="add">子组件按钮</button> </div> </template> <script> export default { props: ['msg'], //从父组件接收msg数据 data() { return { count: 0, } }, methods:{ add(){ this.count++ //自定义事件 this.$emit('numChange',this.count) } } } </script> <style> </style>
-
兄弟组件之间的数据共享
在 vue2.x 中,兄弟组件之间数据共享的方案是 EventBus。
- 在components创建eventsBus.js,并向外共享一个Vue实例对象
- 在数据发送方,调用bus.$emit(‘事件名’,要发送的数据) 方法触发自定义事件
- 在数据的接收方,调用bus.$on(‘事件名’,事件处理函数) 方法注册一个自定义事件。
- 代码实现如下
//eventBus.js
import Vue from 'vue'
//向外共享Vue实例对象
export default new Vue()
//兄弟组件一:Second.vue
<template>
<div>
<button @click="sendMsg">数据发送方</button>
</div>
</template>
<script>
import bus from '@/components/eventBus'
export default {
data() {
return {
msg: 'Best wishes!'
}
},
methods: {
sendMsg() {
//发送数据
bus.$emit('share', this.msg)
}
}
}
</script>
<style>
</style>
//兄弟组件二:Third.vue
<template>
<div>
<p>从Second接收的数据:{{ msgFromSecond }}</p>
</div>
</template>
<script>
import bus from '@/components/eventBus'
export default {
data() {
return {
msgFromSecond: ''
}
},
created() {
//接收数据
bus.$on('share',val =>{
this.msgFromSecond = val
})
}
}
</script>
<style>
</style>
(最后在APP.vue注册Second和Third两个组件,点击数据发送按钮,成功显示接收的数据)
点击后:
更多推荐
已为社区贡献2条内容
所有评论(0)