一、在main.js同級目錄建立一個common.js文件
// 全局變量 const globalObj = {}; // 定義公共變量 globalObj.name = '小明'; // 定義公共方法 globalObj.getAge = function (birthYear) { return new Date().getFullYear() - birthYear; }; export default globalObj
二、在main.js中import這個文件,然后放在Vue原型里
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import Axios from 'axios' // 引入Axios import common from './common' // 引入全局文件common.js Vue.prototype.$axios = Axios; // 全局變量 Vue.prototype.$common = common; // 全局變量 Vue.config.productionTip = false; new Vue({ router, store, render: h => h(App) }).$mount('#app');
三、在組件里使用
<template> <div class="hello"> <h1>{{ msg }}</h1> <h3>{{$common.name}}</h3> <p>{{myAge}}</p> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, computed: { myAge: function () { return this.$common.getAge(1994); } } } </script>
四、頁面輸出
五、思考
這種方式與Vuex起到的作用是一樣的,比Vuex簡單,但是Vuex就是比較專業了。不過還是有深層次的區別的,如下
大神回答: