vue2.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结构
        // 结果为null
        const dom = document.querySelector("#myh3");
        console.log(dom);
        //结果为undefined
        console.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为0
      this.$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,全部满足则返回true
        const 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>

结果为:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值