vue全局方法和屬性的注冊

根據(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('/')">

? ? ? ? &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>

原文:https://blog.csdn.net/qq_36666651/article/details/80302560

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • vue-cli搭建項(xiàng)目 確保安裝了node與npm 再目標(biāo)文件夾下打開終端 執(zhí)行cnpm i vue-cli -g...
    Akiko_秋子閱讀 3,354評論 1 22
  • 基本格式 以json的形式、將數(shù)據(jù)(支持所有格式)掛載在vue的data上、方法掛載在vue的methods上。 ...
    kirito_song閱讀 907評論 0 21
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,168評論 0 29
  • Vue問得最多的面試題 什么是 mvvm? MVVM 是 Model-View-ViewModel 的縮寫。mvv...
    崽崽不哭閱讀 724評論 0 8
  • 世界上第一臺電子數(shù)字式計算機(jī)于1946年2月15日在美國賓夕法尼亞大學(xué)正式投入運(yùn)行,它的名稱叫ENIAC(埃尼阿克...
    殘劍閱讀 463評論 2 6

友情鏈接更多精彩內(nèi)容