【Vue.js学习笔记】14:组件生命周期钩子函数,vue-router路由

版权声明:本文为博主原创学习笔记,如需转载请注明来源。 https://blog.csdn.net/SHU15121856/article/details/85276571

组件生命周期钩子函数

即组件生命周期过程中调用的函数。组件的生命周期可以参考官方文档中的图,这里在前面的例子上修改Header组件,在生命周期的各个方法中弹出对话框演示一下。

Header.vue

<template>
  <header v-on:click="updateTitle">
    <h1>{{title}}</h1>
  </header>
</template>

<script>
  export default {
    name: "Header",
    methods: {
      updateTitle: function () {
        this.title = "新的title";
      }
    },
    data() {
      return {
        title: "点我更新title的值"
      }
    },
    beforeCreate: function () {
      window.alert("组件实例化之前");
    },
    created: function () {
      window.alert("组件实例化完成,但页面还没显示");
    },
    beforeMount: function () {
      window.alert("组件挂载前,页面仍未展示,但虚拟DOM已经配置");
    },
    mounted: function () {
      window.alert("组件挂载后.此方法执行后页面显示");
    },
    beforeUpdate: function () {
      window.alert("组件更新前,页面仍未更新,但虚拟DOM已经配置");
    },
    updated: function () {
      window.alert("组件更新后.此方法执行后页面更新");
    },
    beforeDestroy: function () {
      window.alert("组件销毁前");
    },
    destroyed: function () {
      window.alert("组件销毁后");
    }
  }
</script>

<style scoped>
  header {
    background: lightgreen;
    padding: 10px;
  }

  h1 {
    color: #222;
    text-align: center;
  }

</style>

运行结果略。

vue-router路由

安装vue-router并写到dependencies中(即生产环境也要用它):

npm install vue-router --save

使用npm安装各种包的区别见这篇

main.js

在这里导入前面安装的路由插件,并配置和使用它建立到不同组件的路由。

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
//路由模块
import VueRouter from 'vue-router'
//导入要使用的组件
import HelloWorld from './components/HelloWorld'
import Home from './components/Home'

Vue.config.productionTip = false;
//使用路由模块
Vue.use(VueRouter);

//配置路由,传入配置对象
const router = new VueRouter({
  routes: [
    {path: "/", component: Home},
    {path: "/hello", component: HelloWorld},
  ],
  mode: "history",//可以去掉url中的"#/"
});


/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: {App},
  template: '<App/>',
  router,//在这里使用它
});

App.vue的template

这里是根组件,有特殊的地位,不再去直接调用组件展示页面,而是在这里放置了导航和路由视图。

<template>
  <div id="app">
    <!--导航部分-->
    <ul>
      <!--<li><a href="/">Home</a></li>-->
      <!--<li><a href="/hello">Hello</a></li>-->
      <li>
        <router-link to="/">Home</router-link>
      </li>
      <li>
        <router-link to="/hello">Hello</router-link>
      </li>
    </ul>
    <!--随路由变化的部分-->
    <router-view></router-view>
  </div>
</template>

在实现导航时先用a标签做了一个简易实现,可以发现a标签不管点击了多少次,点击了都会导致重新加载。

换成router-link标签并在to属性中指定路由,这时就不会再重复加载了,可以提升效率。

这里我像视频里一样Chrome浏览器试了一下的确没问题,但用到QQ浏览器里,第一次点击还是会加载一下。这个问题不知道咋回事,感觉是浏览器这个动画的触发条件可能不一样。

运行结果

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/SHU15121856/article/details/85276571