前端设计

Vue.prototype的使用

2023-04-06

Vue.prototype的使用


它是就是解决 替换全局使用的一个标识。

以 $ 开头,$ 是在 Vue 所有实例中都可用的 property 的一个简单约定。这样做会避免和已被定义的数据、方法、计算属性产生冲突。


例如:

来自真实项目。在main.js 或app.vue里声明一个自定义组件日期选择。

import datePicker from './ components/datePicker'

//这里就是全局替换 datePicker 的标识

Vue.prototype.$datepicker = datePicker;


Vue.prototype的使用:

this.$xxx , 可以赋值,替换某个属性

this.$datePicker


其他应用示例:axios

npm install vue-axios --save

npm install qs.js --save  

//它的作用是能把 json 格式的直接转成 data 所需的格式


// mian.js 中

import Vue from 'vue'

import axios from 'axios'

import qs from 'qs'

 

Vue.prototype.$axios = axios    //全局注册,使用方法为:this.$axios

Vue.prototype.qs = qs           //全局注册,使用方法为:this.qs


// 相应组件 中

<script>

  export default{

    data(){

      return{

        userId:666,         

        token:'',

      }

    },

    created(){

      this.$axios({

        method:'post',

        url:'api',

        data:this.qs.stringify({    //这里是发送给后台的数据

          userId:this.userId,

          token:this.token,

        })

      }).then((response) =>{          //这里使用了ES6的语法

        console.log(response)       //请求成功返回的数据

      }).catch((error) =>{

        console.log(error)       //请求失败返回的数据

      })

    }

  }

</script>