1.View.prototype
Vue.prototype.$axios = axios
//this.$axios
2.Vue.use()
//在使用 element时会先import,再Vue.use()一下,实际上就是注册组件,触发 install 方法;
Vue.use(Element)
window.$ = require("jquery") //挂载在window上
3.View.directive()
//防止按钮重复点击,全局使用 v-preventClick
Vue.directive('preventClick', {
inserted (el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true
setTimeout(() => {
el.disabled = false
}, 3000)
}
})
}
})
4.View.component()
グローバルコンポーネントは通常のコンポーネントに基づいており、通常のコンポーネントをDOMに作成するだけです
//dragResize.js
import VueDragResize from 'vue-drag-resize'
export default {
install() {
Vue.component("VueDragResize",VueDragResize)
}
};
//main.js
import VueDragResize from './utils/dragResize.js'
Vue.use(VueDragResize)
//需要导入多个组件
const requireComponent = require.context('./components', false, /\.(vue|js)$/)
requireComponent.keys().forEach((fileName) => {
// 获取组件配置
const componentConfig = requireComponent(fileName)
const componentName = fileName.split('/').pop().split(".")[0]
// 全局注册组件
Vue.component(componentName, componentConfig.default)
})
//说明
require.context(directory,useSubdirectories,regExp)
接收三个参数:
directory:说明需要检索的目录
useSubdirectories:是否检索子目录
regExp: 匹配文件的正则表达式,一般是文件名
5.View.extend()
一部の
Vueコンポーネントは、一部の要素を要素にマウントする必要があります。この時点で、extendは機能します。Vue.extend()を使用してVueサブクラスインスタンスを構築し、mount()メソッドを呼び出して必要なDOMを生成してから、対応するelインスタンスがDOMに挿入されます
import Vue from 'vue'
const toastMessage = Vue.extend({
template: '<div>{
{ text }}</div>',
data: function () {
return {
text: '发信息来啦'
}
}
})
const message = new toastMessage().$mount()
document.body.appendChild(message.$el)
6.View.filter()
差分式の値は左から右に渡され、前の値はパラメーターとして後ろに渡され、パイプ文字で区切られます。
<div id="app">
<p>{
{price | addPriceIcon | editPrice}}</p>
</div>
let vm = new Vue({
el:"#app",
data:{
price:200
},
filters:{
addPriceIcon(value){
return '¥' + value
},
editPrice(value){
console.log(value)
return "吃饭:" + value
}
}
})
使い方は?
他の人のコンポーネントをVueで使用する場合、多くの人がVue.use()を使用すると思います。例:Vue.use(VueRouter)、Vue.use(MintUI)。ただし、axiosを使用する場合は、Vue.use(axios)を使用する必要はなく、直接使用できます。では、これはなぜですか?
axiosはインストール方法を使用しないため
export default {
install(Vue) {
Vue.prototype.$get = (url, params = {
}) => {
return new Promise((resolve, reject) => {
axios.get(url, params)
.then(response => resolve(response.data))
.catch(error => reject(error))
})
}
Vue.prototype.$post = (url, params = {
}) => {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => resolve(response.data))
.catch(error => reject(error))
})
}
}
}