混合是什么
混合 (mixins) 是一種分發 Vue 組件中可復用功能的非常靈活的方式。混合對象可以包含任意組件選項。以組件使用混合對象時,所有混合對象的選項將被混入該組件本身的選項。
例如:
var tpl1={ template:'#stpl1', data:function(){ return {msg:false} }, methods:{ msgf:function(){ this.msg=!this.msg } }}var tpl2={ template:'#stpl2', data:function(){ return {msg:false} }, methods:{ show:function(){ this.msg=true }, hide:function(){ this.msg=false } }}new Vue({ el:'#box', components:{ tpla:tpl1, tplb:tpl2, }})我們會發現,兩個組件中的數據大多數相同,這是我們可以將它們進行混合
// 首先,定義一個混合對象var mymixin = { data:function(){ return {msg:false} }, methods:{ show:function(){ this.msg=true }, hide:function(){ this.msg=false }, msgf:function(){ this.msg=!this.msg } }}var tpl1={ template:'#stpl1', minins:[mymixin]}var tpl2={ template:'#stpl2', minins:[mymixin]}// 如果我們需要在第一個組件定義data為true時,我們可以直接在組件內定義,他會覆蓋mixin的datavar tpl1={ template:'#stpl1', minins:[mymixin], data:function(){ msg:true }}自定義指令
除了默認設置的核心指令( v-model 和 v-show ),Vue 也允許注冊自定義指令。注意,在 Vue2.0 里面,代碼復用的主要形式和抽象是組件——然而,有的情況下,你仍然需要對純 DOM 元素進行底層操作,這時候就會用到自定義指令。
// 注冊一個全局自定義指令 v-focusVue.directive('focus', { // 當綁定元素插入到 DOM 中。 inserted: function (el) { // 聚焦元素 el.focus() }})也可以注冊局部指令,組件中接受一個 directives 的選項:
directives: { focus: { // 指令的定義--- }}然后你可以在模板中任何元素上使用新的 v-focus 屬性:
<input v-focus>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選