根據(jù)JavaScript原型鏈的原理,我們可以將全局變量和方法掛在在Vue的父類上,即使用Vue.prototype來掛載。?
例如我們想講一個路由跳轉(zhuǎn)方法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/>'
});
---------------------
這時候我們就可以在別的組件直接調(diào)用了,而不需要額外的聲明,如下兩種調(diào)用方法<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('/')">
? ? ? ? ×
? ? ? </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>
原文:https://blog.csdn.net/qq_36666651/article/details/80302560