vue知識點(mst)彙總(三)
阿新 • • 發佈:2021-01-14
11.vue路由的鉤子函式
首頁可以控制導航跳轉,beforeEach,afterEach等,一般用於頁面title的修改。一些需要登入才能調整頁面的重定向功能。
beforeEach主要有3個引數to,from,next:
to:route即將進入的目標路由物件,
from:route當前導航正要離開的路由
next:function一定要呼叫該方法resolve這個鉤子。執行效果依賴next方法的呼叫引數。可以控制網頁的跳轉。
12.vue-cli如何新增自定義指令?
(1)建立區域性指令
var app = new Vue({
el: ‘#app’,
},
// 建立指令(可以多個)
directives: {
// 指令名稱
dir1: {
inserted(el) {
// 指令中第一個引數是當前使用指令的DOM
console.log(el);
console.log(arguments);
// 對DOM進行操作
el.style.width = ‘200px’;
el.style.height = ‘200px’;
el.style.background = ‘#000’;
}
}
}
})
(2)全域性指令
Vue.directive(‘dir2’, {
inserted(el) {
console.log(el);
}
})
(3)指令的使用
13.vue如何自定義一個過濾器?
html程式碼: <div id="app"> <input type="text" v-model="msg" /> {{msg| capitalize }} </div> JS程式碼: var vm=new Vue({ el:"#app", data:{ msg:'' }, filters: { capitalize: function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } } }) 全域性定義過濾器 Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) }) 過濾器接收表示式的值 (msg) 作為第一個引數。capitalize 過濾器將會收到 msg的值作為第一個引數。
14.keep-alive
keep-alive是 Vue 內建的一個元件,可以使被包含的元件保留狀態,或避免重新渲染。
在vue 2.1.0 版本之後,keep-alive新加入了兩個屬性: include(包含的元件快取) 與 exclude(排除的元件不快取,優先順序大於include) 。
使用方法
<keep-alive include='include_components' exclude='exclude_components'>
<component>
<!-- 該元件是否快取取決於include和exclude屬性 -->
</component>
</keep-alive>
引數解釋
include - 字串或正則表示式,只有名稱匹配的元件會被快取
exclude - 字串或正則表示式,任何名稱匹配的元件都不會被快取
include 和 exclude 的屬性允許元件有條件地快取。二者都可以用“,”分隔字串、正則表示式、陣列。當使用正則或者是陣列時,要記得使用v-bind 。
使用示例
<!-- 逗號分隔字串,只有元件a與b被快取。 -->
<keep-alive include="a,b">
<component></component>
</keep-alive>
<!-- 正則表示式 (需要使用 v-bind,符合匹配規則的都會被快取) -->
<keep-alive :include="/a|b/">
<component></component>
</keep-alive>
<!-- Array (需要使用 v-bind,被包含的都會被快取) -->
<keep-alive :include="['a', 'b']">
<component></component>
</keep-alive>
15.v-if 和 v-show 區別
v-if按照條件是否渲染,v-show是display的block或none;