vue api強化學習之-------全局api
Vue提供的一套靜態方法
Vue.use
Vue.use( plugin )
註冊vue插件,插件可以是一個對象或者函數,若爲對象時,必須提供install方法;若爲函數時,它會被作爲install方法使用,install方法被調用時,Vue會被作爲參數傳入。
此方法必須在調用創建根實例的new Vue()之前調用;
import Vue from 'vue'
import App from './App.vue'
import Router from 'vue-router'
// 創建根實例之前 註冊路由插件
Vue.use(Router);
// 創建路由實例
var router = new Router({
mode:'history',
routes:[
{
path:'/',
component:xx
},
]
})
// 將路由實例傳入vue根組件
new Vue({
router,
render: h => h(App),
}).$mount('#app')
Vue.component
用法:Vue.component( id, [definition] )
id,給註冊的組件一個唯一標識,此id在註冊的過程中也被被設置成組件名稱;definition爲註冊組件時的配置選項。
註冊或獲取全局組件,當值傳入id時時獲取,兩個參數都傳入時是註冊組件;
Vue.directive
用法:Vue.directive( id, [definition] )
參數形式同Vue.component
註冊或獲取全局指令
Vue.filter
用法:Vue.filter( id, [definition] )
參數形式同Vue.component
註冊或後去全局過濾器
Vue.mixin
語法:Vue.mixin( mixin )
全局註冊一個混入,影響註冊之後所有創建的每個 Vue 實例。插件作者可以使用混入,向組件注入自定義的行爲。不推薦在應用代碼中使用
Vue.extend
語法:Vue.extend( options )
使用基礎 Vue 構造器,創建一個新的Vue子類構造器,參數是一個包含組件選項的對象。
data 選項是特例,需要注意 - 在 Vue.extend() 中它必須是函數
// 創建構造器
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// 創建 Profile 實例,並掛載到一個元素上。
new Profile().$mount('#app')
以上幾個常用方法示例
- main.js
import Vue from 'vue'
import App from './App.vue'
import fistdemo from './views/definecomp.vue'
import msgboxVue from './views/messageBoxExtend/messageBox.vue';
/*********************註冊全局指令************************** */
// 註冊一個全局自定義指令 `v-focus`
Vue.directive('focus', {
// 當被綁定的元素插入到 DOM 中時……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
/*********************註冊全局插件************************** */
// 全局註冊自定義插件
const compo = {
// 添加install方法,第一個參數必須是Vue
install:function(Vue){
Vue.component("first-demo",fistdemo)
}
}
// 插件是一個對象時,必須有install方法
Vue.use(compo)
/*********************註冊全局過濾器************************** */
Vue.filter("capitalize",function(value){
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
/*********************全局混入************************** */
Vue.mixin({
created:function(){
console.log('全局混入。。。。。')
},
errorCaptured:function(a,b){
return false;
},
methods:{
alertInfo(msg){
alert(msg)
}
}
})
/*********************此插件中利用Vue.extend構建子類構造器,構建了一個插件************************** */
// 定義插件對象
const MessageBox = {};
// vue的install方法,用於定義vue插件
MessageBox.install = function (Vue, options) {
// 構造一個新的Vue構造器
const MessageBoxInstance = Vue.extend(msgboxVue);
let currentMsg;
const initInstance = () => {
// 實例化vue實例
currentMsg = new MessageBoxInstance();
let msgBoxEl = currentMsg.$mount().$el;
document.body.appendChild(msgBoxEl);
};
// 在Vue的原型上添加實例方法,以全局調用
Vue.prototype.$msgBox = {
showMsgBox (options) {
if (!currentMsg) {
initInstance();
}
if (typeof options === 'string') {
currentMsg.content = options;
} else if (typeof options === 'object') {
Object.assign(currentMsg, options);
}
// Object.assign方法只會拷貝源對象自身的並且可枚舉的屬性到目標對象
return currentMsg.showMsgBox()
.then(val => {
currentMsg = null;
return Promise.resolve(val);
})
.catch(err => {
currentMsg = null;
return Promise.reject(err);
});
}
};
};
Vue.use(MessageBox); //封裝的messagebox組件 通過this調用
new Vue({
render: h => h(App),
}).$mount('#app')
- definecomp.vue 插件一
此文件中定義一個非常簡單的插件,在main.js中全局註冊,在應用組件中應用即可
<template>
<div class="definedcomp">
<div>{{msg}}</div>
</div>
</template>
<script>
export default {
name: 'fist-demo',
data(){
// 根級響應式屬性,全部在此處聲明
return {
msg:'我是全局註冊的組件'
}
},
}
</script>
- messageBox.vue 插件二
定義一個全局組件,並在man.js中利用vue.extend,Vue.prototype,vue.use註冊爲一個全局插件
<template>
<div class="dialog_views" v-show="isShowMessageBox" @touchmove.prevent>
<div class="UImask" @click="cancel"></div>
<transition name="confirm-fade">
<div class="UIdialog" v-show="isShowMessageBox">
<div class="UIdialog_hd">{{title}}</div>
<div class="UIdialog_bd">
<slot>{{content}}</slot>
</div>
<div :class="[ isShowCancelBtn ? 'UIdialog_ft' : 'UIdialog_ft UIdialog_ft_one']">
<span v-if="isShowCancelBtn" class="UIdialog_btn" @click="cancel">{{cancelVal}}</span>
<span v-if="isShowConfimrBtn" class="UIdialog_btn" @click="confirm">{{confirmVal}}</span>
</div>
</div>
</transition>
</div>
</template>
<script>
export default {
components: {
},
data() {
return {
isShowMessageBox: false,
resolve: '',
reject: '',
promise: '', // 保存promise對象
};
},
props: {
isShowConfimrBtn: {
type: Boolean,
default: true
},
content: {
type: String,
default: '這是彈框內容'
},
isShowCancelBtn: { //是否展示取消按鈕
type: Boolean,
default: true
},
title: { //標題
type: String,
default: '提示',
},
confirmVal: {
type: String, //確認文字
default: '確定'
},
cancelVal: { //取消文字
type: String,
default: '取消'
},
maskHide: {
type: Boolean, //是否可以點擊蒙層關閉
default: true
}
},
methods: {
// 確定,將promise斷定爲resolve狀態
confirm() {
this.isShowMessageBox = false;
this.resolve('confirm');
this.remove();
},
// 取消,將promise斷定爲reject狀態
cancel() {
this.isShowMessageBox = false;
this.reject('cancel');
this.remove();
},
// 彈出messageBox,並創建promise對象
showMsgBox() {
this.isShowMessageBox = true;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
// 返回promise對象
return this.promise;
},
remove() {
setTimeout(() => {
this.destroy();
}, 100);
},
destroy() {
this.$destroy();
document.body.removeChild(this.$el);
},
}
};
</script>
<style scoped>
.UImask {
position: fixed;
z-index: 999;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
}
.UIdialog {
position: fixed;
z-index: 999;
width: 80%;
max-width: 400px;
display: table;
z-index: 5000;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
transition: opacity 0.3s, transform 0.4s;
text-align: center;
border-radius: 8px;
overflow: hidden;
background: #fff;
padding: 30px 40px;
}
.UIdialog_hd {
font-weight: bold;
font-size: 34px;
letter-spacing: 1px;
}
.UIdialog_bd {
margin: 40px 0;
text-align: center;
font-size: 24px;
}
.UIdialog_bd p{
display: inline-block;
text-align:left;
}
.UIdialog_ft {
position: relative;
font-size: 28px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
justify-content: space-between;
margin: 0 20px;
margin-bottom: -5px;
padding-top: 15px;
}
.UIdialog_btn {
display: block;
text-decoration: none;
position: relative;
display: block;
background-color: #000;
border-radius: 40px;
padding: 12px 45px;
}
.UIdialog_ft_one {
text-align: center;
justify-content: center;
}
/* 進入和出去的動畫 */
.confirm-fade-enter-active {
animation: bounce-in 0.5s;
}
.confirm-fade-leave-active {
animation: bounce-in 0.5s reverse;
}
.confirm-fade-enter,
.confirm-fade-leave-to {
opacity: 0;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
</style>
- overallApi.vue 應用組件
應用自定義的插件
<template>
<div class="overall">
<!-- 使用全局註冊的插件 -->
<first-demo></first-demo><br/>
<!-- 使用全局指令 -->
<input type="text" v-focus><br/>
<!-- 使用全局過濾器,格式化字符串 -->
<div>{{str | capitalize}}</div><br/>
<!-- 使用全局混入功能 -->
<button @click="submit"> 提交</button><br/>
<!-- 使用Vue.extend 構造器構造的全局插件-->
<button @click="confirm"> 提交</button><br/>
</div>
</template>
<script>
export default {
name: 'OverallApi',
data(){
// 根級響應式屬性,全部在此處聲明
return {
str:'capitalize'
}
},
methods:{
submit(){
//提交數據。。。省略
this.alertInfo("報錯了");
},
confirm(){
this.$msgBox.showMsgBox({
title: '提示',
content: '確定要刪除嗎',
}).then(async (val) => {
// ...
console.log('確認')
}).catch(() => {
// ...
console.log('取消')
});
}
},
mounted(){
console.log(this,".......this.$data........")
}
}
</script>
Vue.nextTick
語法: Vue.nextTick( [callback, context] )
在下次 DOM 更新循環結束之後執行延遲迴調。在修改數據之後立即使用這個方法,獲取更新後的 DOM
同 vm.$nextTick類似
// 修改數據
vm.msg = 'Hello'
// DOM 還沒有更新
Vue.nextTick(function () {
// DOM 更新了
})
Vue.set
語法:Vue.set( target, propertyName/index, value )
向響應式對象中添加一個屬性,並確保這個新屬性同樣是響應式的,且觸發視圖更新。它必須用於向響應式對象上添加新屬性,因爲 Vue 無法探測普通的新增屬性,注意對象不能是 Vue 實例,或者 Vue 實例的根數據對象
Vue.delete
語法:Vue.delete( target, propertyName/index )
刪除對象的屬性。如果對象是響應式的,確保刪除能觸發更新視圖。這個方法主要用於避開 Vue 不能檢測到屬性被刪除的限制,但是你應該很少會使用它
目標對象不能是一個 Vue 實例或 Vue 實例的根數據對象
Vue.compile
Vue.compile( template )
在 render 函數中編譯模板字符串。只在獨立構建時有效
Vue.version
獲取Vue的安裝版本號
Vue.observable
Vue.observable( object )
讓一個對象可響應。Vue 內部會用它來處理 data 函數返回的對象。
返回的對象可以直接用於渲染函數和計算屬性內,並且會在發生改變時觸發相應的更新。也可以作爲最小化的跨組件狀態存儲器