当前位置: 代码迷 >> 综合 >> vue2.0-生命周期、数据共享
  详细解决方案

vue2.0-生命周期、数据共享

热度:84   发布时间:2023-11-25 13:27:10.0

目录

1. 组件的生命周期

1)生命周期、生命周期函数

2)组件生命周期函数的分类

2. 组件之间的数据共享

1)组件之间的关系

2)父子组件之间的数据共享

1??父组件向子组件共享数据

2??子组件向父组件共享数据

3)兄弟组件之间的数据共享

1??EventBus的使用步骤

3. ref引用

1)ref引用

2)使用ref引用组件实例

3)控制文本框和按钮的按需切换

4)让文本框自动获得焦点

5)this.$nextTick(cb)方法

4. 数组中的方法

1)some循环

2)every循环

3)reduce方法


1. 组件的生命周期

1)生命周期、生命周期函数

生命周期:指一个组件从创建->运行->销毁的整个阶段,强调的是一个时间段。

生命周期函数:是由vue框架提供的内置函数,会伴随着组件的生命周期,自动按次序执行

2)组件生命周期函数的分类

生命周期示图:

<template><div><h3 id="myh3">Test.vue组件 -- {
   { books.length }}本图书</h3><p id="page">{
   { message }}</p><button @click="message += '~'">修改message的值</button></div>
</template><script>
export default {props: ['info'],data() {return {message: 'msg',// 定义books数组,存储的是所有图书的列表数据,默认为空数组books: []}},methods: {show() {console.log('调用的Test组件的show()方法');},//利用Ajax请求得到数据initBooklist() {const res = new XMLHttpRequest() res.addEventListener('load', () => {const result = JSON.parse(res.responseText)// console.log(result);this.books = result.data})res.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')res.send()}},beforeCreate() {// 组件的props、data、methods处于未创建状态,所以都不可用// console.log(this.info);// console.log(this.message);// this.show()},created() {// console.log(this.info);// console.log(this.message);// this.show();//经常调用methods里面的方法,请求服务器的数据//并且把请求到的数据转存到data中,供template模版渲染的时候用this.initBooklist();//不能操作dom,因为还未生成模版结构// const dom = document.querySelector("#myh3");// console.log(dom);},beforeMount() {// 要把在内存中编译好的HTML结构渲染到浏览器中//此时浏览器中还没有当前组件的DOM结构// 结果为nullconst dom = document.querySelector("#myh3");console.log(dom);//结果为undefinedconsole.log(this.$el);},mounted() {// 把在内存中编译好的HTML结构,替换掉el指定的DOM元素console.log(this.$el);//此时浏览器中已经包含了当前组件的DOM结构//如果要操作DOM元素,最早只能在mounted阶段执行const dom = document.querySelector("#myh3");console.log(dom);},beforeUpdate() {console.log('beforeUpdate');// 最新的数据console.log(this.message);// 此时最新的数据还没有渲染到页面中const dom = document.querySelector("#page");console.log(dom.innerHTML);},updated() {console.log('updated');// 最新的数据console.log(this.message);// 此时最新的数据已经渲染到页面中const dom = document.querySelector("#page");console.log(dom.innerHTML);},beforeDestroy() {// 将要销毁此组件,此时还未销毁,组件还处于正常工作的状态console.log('beforeDestroy');console.log(this.message);},destroyed() {console.log('destroyed');}}
</script><style lang="less" scoped>div {height: 200px;background-color: pink;}
</style>

2. 组件之间的数据共享

1)组件之间的关系

组件之间最常见的关系:

  1. 父子关系
  2. 兄弟关系

 

2)父子组件之间的数据共享

父子组件之间的数据共享:

  1. 父 -> 子共享数据
  2. 子 -> 父共享数据

1??父组件向子组件共享数据

父组件向子组件共享数据需要使用自定义属性

父组件:App.vue

<template><div id="app"><h1>App 根组件</h1><hr><!-- 父组件 --><Left :msg="message" :user="userinfo"></Left></div>
</template><script>import Left from '@/components/Left.vue'export default {data() {return {message: 'hello world',userinfo: {name: 'zs',age: 18}}},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>

 

结果为:

 

2??子组件向父组件共享数据

子组件向父组件共享数据使用自定义事件

父组件:App.vue

<template><div id="app"><h1>App 根组件 --- {
   { countFromRight }}</h1><hr><div class="box"><!-- 父组件 --><Left :msg="message" :user="userinfo"></Left><!-- 触发事件 --><Right @numchange="getNewCount"></Right></div></div>
</template><script>import Left from '@/components/Left.vue'
import Right from '@/components/Right.vue'export default {data() {return {message: 'hello world',userinfo: {name: 'zs',age: 18},countFromRight: 0}},components: {Left,Right},methods: {// 获取子组件传递过来的数据getNewCount(val) {this.countFromRight = val}}
}
</script>

子组件:Right.vue

<template><div class="right-container"><h3>Right 组件 --- {
   { count }} </h3><button @click="add">+1</button></div>
</template><script>
export default {data() {return {count: 0}},methods: {add() {this.count += 1;//修改的结果传给父组件,$emit()自定义事件this.$emit('numchange', this.count)}}
}
</script>

结果为:

 

 

3)兄弟组件之间的数据共享

在vue2.x中,兄弟组件之间数据共享的方案是EventBus

1??EventBus的使用步骤

  1. 创建eventBus.js模块,并向外共享一个Vue的实例对象
  2. 在数据发送方,调用bus.$emit('事件名称',要发送的数据)方法触发自定义事件
  3. 在数据接收方,调用bus.$on('事件名称',要发送的数据)方法注册一个自定义事件

eventBus.js

import Vue from 'vue'//向外共享Vue的实例对象
export default new Vue()

数据发送方Left.vue

<template><div class="left-container"><h3>Left 组件</h3><p>父组件传过来的msg是: {
   { msg }}</p><p>父组件传过来的user是: {
   { user }}</p><hr><button @click="send">把str发送给Right</button></div>
</template><script>
//1.导入eventBus.js模块
import bus from './eventBus.js'export default {props: ['msg', 'user'],data() {return {str: 'hello world'}},methods: {send() {//2.通过eventBus来发送数据bus.$emit('share', this.str)}}
}</script><style lang="less">
.left-container {padding: 0 20px 20px;background-color: orange;min-height: 250px;flex: 1;
}
</style>

数据接收方Right.vue

<template><div class="right-container"><h3>Right 组件 --- {
   { count }} </h3><button @click="add">+1</button><p>{
   { strFromLeft }}</p></div>
</template><script>
//1.导入eventBus.js模块
import bus from './eventBus.js'export default {data() {return {count: 0,strFromLeft: ''}},methods: {add() {this.count += 1;//修改的结果传给父组件,$emit()自定义事件this.$emit('numchange', this.count)}},created() {// 2.为bus绑定注册事件bus.$on('share', (val) => {console.log('在Right中定义的share被激发了' + val);this.strFromLeft = val;})}
}
</script><style lang="less">
.right-container {padding: 0 20px 20px;background-color: lightskyblue;min-height: 250px;flex: 1;
}
</style>

结果为:

 

3. ref引用

1)ref引用

ref用来辅助开发者在不依赖于jQuery的情况下,获取DOM元素或组件的引用。

每个vue的组件实例上,都包含一个$refs对象,里面存储着对应的DOM元素或组件的引用。默认情况下,组件的$refs对象指向一个空对象

<template><div id="app"><h1 ref="myh1">App 根组件</h1><button @click="showThis">点击</button><hr><div class="box"></div></div>
</template><script>export default {methods: {showThis() {// this是vue实例对象,组件的$refs对象指向一个空对象console.log(this);//得到{ myh1:h1 }console.log(this.$refs);//得到DOM元素:<h1 ref="myh1">App 根组件</h1>console.log(this.$refs.myh1);//得到DOM元素之后就可以修改DOM元素的样式this.$refs.myh1.style.color = 'red';}}
}
</script><style lang="less">
#app {padding: 1px 20px 20px;background-color: #efefef;
}
.box {display: flex;
}
</style>

结果为:

 

2)使用ref引用组件实例

如果想要使用ref引用页面上的组件实例,则可以按照如下的方式进行操作:

 

App.vue

<template><div id="app"><h1 ref="myh1">App 根组件</h1><button @click="showThis">点击</button><button @click="resetLeft">重置Left组件的count为0</button><hr><div class="box"><!-- 使用ref引用页面上的组件实例 --><Left ref="comLeft"></Left></div></div>
</template><script>import Left from './components/Left.vue'export default {methods: {showThis() {// this是vue实例对象,组件的$refs对象指向一个空对象console.log(this);//得到Left组件的count值console.log(this.$refs.comLeft.count);//得到{ myh1:h1 }// console.log(this.$refs);//得到DOM元素:<h1 ref="myh1">App 根组件</h1>// console.log(this.$refs.myh1);//得到DOM元素之后就可以修改DOM元素的样式this.$refs.myh1.style.color = 'red';},resetLeft() {//重置Left组件的count为0this.$refs.comLeft.count = 0}},components: {Left}
}
</script><style lang="less">
#app {padding: 1px 20px 20px;background-color: #efefef;
}
.box {display: flex;
}
</style>

Left.vue

<template><div class="left-container"><h3>Left 组件 - {
   { count }}</h3><button @click="count += 1">+1</button><button @click="resetCount">重置</button></div>
</template><script>export default {data() {return {count: 0}},methods: {resetCount() {this.count = 0}}
}</script><style lang="less">
.left-container {padding: 0 20px 20px;background-color: orange;min-height: 250px;flex: 1;
}
</style>

结果为:

 

3)控制文本框和按钮的按需切换

通过布尔值inputVisible来控制组件中的文本框与按钮的按需切换。

4)让文本框自动获得焦点

当文本框展示出来之后,如果希望它立即获得焦点,则可以为其添加ref引用,并调用原生DOM对象的.focus()方法即可。

<input type="text" v-if="inputVisible" @blur="showButton" ref="inputRef">
<button v-else @click="showInput">展示输入框</button><script>export default {methods: {showInput() {//点击按钮,展示输入框this.inputVisible = true//调用文本框的DOM引用,并使其获得焦点this.$refs.inputRef.focus()},showButton() {//当输入框失去焦点的时候,展示按钮this.inputVisible = false}}
}
</script>

5)this.$nextTick(cb)方法

组件的$nextTick(cb)方法,会把cb回调推迟到下一个DOM更新周期之后执行。通俗的理解:等组件的DOM更新完成之后,再执行cb回调函数,从而保证cb回调函数可以操作到最新的DOM元素。

<input type="text" v-if="inputVisible" @blur="showButton" ref="inputRef">
<button v-else @click="showInput">展示输入框</button><script>export default {methods: {showInput() {//点击按钮,展示输入框this.inputVisible = true//调用文本框的DOM引用,并使其获得焦点// $nextTick(cb)方法,会把cb回调推迟到下一个DOM更新周期之后执行this.$nextTick( () => {this.$refs.inputRef.focus()})}
}
</script>

4. 数组中的方法

1)some循环

    <script>const arr = ['春', '夏', '秋', '冬', '四季'];//1.forEach():一旦开始,就会一直执行到整个数组结束,无法在中间停止// arr.forEach((item, index) => {//     if(item == '夏') {//         console.log(index);//     }// })//2.some():在找到对应的项之后,可以通过return true来终止循环arr.some((item, index) => {console.log(1);if(item == '夏') {console.log(index);return true;}})    </script>

结果为:

 

2)every循环

   <script>const arr = [{id: 1, name: '春', state: true},{id: 2, name: '夏', state: false},{id: 3, name: '秋', state: true}]//every():只要有一项不满足条件就返回false,全部满足则返回trueconst result = arr.every(item => item.state);console.log(result);</script>

结果为:

 

3)reduce方法

    <script>const arr = [{id: 1, name: '草莓', state: true, price: 20, count:1},{id: 2, name: '芒果', state: false, price: 30, count:2 },{id: 3, name: '西瓜', state: true, price: 40, count:3}]//总价// let amount = 0;//把state为true的商品总价相加// arr.filter(item => item.state).forEach(item => {//     amount += item.price * item.count;// })// console.log(amount);// arr.filter(item => item.state).reduce((累加的结果和, 当前循环项) =>{}, 初始值)const result = arr.filter(item => item.state).reduce((amount, item) => {return amount += item.price * item.count;},0);//简写// const result = arr.filter(item => item.state).reduce((amount,item) => amount += item.price * item.count,0)console.log(result);</script>

结果为: