vue定义全局变量和全局方法

时间:2019-09-08 09:32:33 类型:vue
字号:    

一、全局引入文件

1、先定义共用组件 common.vue

    

<script type="text/javascript">
    // 定义一些公共的属性和方法
    const baseUrl = 'http://www.ncyteng.com/'
    function getMyname() {
        console.log("南昌雅腾")
    }
    // 暴露出这些属性和方法
    export default {
        baseUrl,
        getMyname
    }
</script>
2.  直接在单个.vue文件中使用

<script lang="ts">
import { Component, Vue ,Watch } from 'vue-property-decorator';
import Nav from './Nav.vue';
import globals from '../components/common.vue'
@Component({
  components: {
    Nav,
  },
})

export default class Home extends Vue {
	 title:string = "南昌雅腾首页";
	 content:string="";
	 classid:number=0;
	 mounted(){
	 	   console.log(globals.baseUrl);
           $("title").html(this.title);
      }
     created(){
     	
     }
}
</script>

二、main.js/main.tsyywr中引入全局变量和方法

     1. 定义common.vue同上

    2. main.ts文件中引入并赋值

import globals from './components/common'
Vue.prototype.globals = globals
  3. 直接在.vue文件中引用
export default class Home extends Vue {
	 title:string = "南昌雅腾首页";
	 content:string="";
	 classid:number=0;
	 mounted(){
	 	   console.log(this.globals.baseUrl);
           $("title").html(this.title);
      }
     created(){
     	
     }
}