根据JavaScript原型链的原理,我们可以将全局变量和方法挂在在Vue的父类上,即使用Vue.prototype来挂载。
例如我们想讲一个路由跳转方法toPath能够全局使用,但又不想每个组件去声明定义一遍,那我们就直接将其挂在Vue.prototype上。
我们在main.js声明Vue时将其挂载上:

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
Vue.prototype.toPath = function (path) {
  this.$router.push(path);
};

new Vue({
  el: '#app',
  router,
  components: { App},
  template: '<App/>'
});

这时候我们就可以在别的组件直接调用了,而不需要额外的声明,如下两种调用方法。

<template>
  <div class="align-content-center">
    <p>博客地址
      <!--<button type="button" class="close" aria-hidden="true" @click="jump">-->
      <button type="button" class="close" aria-hidden="true" @click="toPath('/')">
        &times;
      </button>
      https://blog.csdn.net/qq_36666651?ref=toolbar
    </p>
  </div>
</template>

<script>
  export default {
    name: "blog",
    methods: {
      jump: function () {
        this.toPath("/");
      }
    }
  }
</script>

<style scoped>

</style>
Logo

前往低代码交流专区

更多推荐