国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

vue mixins組件復用的幾種方式(小結)

2019-11-19 15:32:27
字體:
來源:轉載
供稿:網友

最近在做項目的時候,研究了mixins,此功能有妙處。用的時候有這樣一個場景,頁面的風格不同,但是執行的方法,和需要的數據非常的相似。我們是否要寫兩種組件呢?還是保留一個并且然后另個一并兼容另一個呢?

不管以上那種方式都不是很合理,因為組件寫成2個,不僅麻煩而且維護麻煩;第二種雖然做了兼容但是頁面邏輯造成混亂,必然不清晰;有沒有好的方法,有那就是用vue的混合插件mixins。混合在Vue是為了提出相似的數據和功能,使代碼易懂,簡單、清晰。

1.場景

假設我們有幾個不同的組件,它們的工作是切換狀態布爾、模態和工具提示。這些提示和情態動詞不有很多共同點,除了功能:他們看起來不一樣,他們不習慣相同,但邏輯是相同的。

//彈框const Modal = { template: '#modal', data() {  return {   isShowing: false  } }, methods: {  toggleShow() {   this.isShowing = !this.isShowing;  } }, components: {  appChild: Child }}//提示框const Tooltip = { template: '#tooltip', data() {  return {   isShowing: false  } }, methods: {  toggleShow() {   this.isShowing = !this.isShowing;  } }, components: {  appChild: Child }}

上面是一個彈框和提示框,如果考慮做2個組件,或者一個兼容另一個都不是合理方式。請看一下代碼

const toggle = { data() {  return {   isShowing: false  } }, methods: {  toggleShow() {   this.isShowing = !this.isShowing;  } }}const Modal = { template: '#modal', mixins: [toggle], components: {  appChild: Child }};const Tooltip = { template: '#tooltip', mixins: [toggle], components: {  appChild: Child }};

用mixins引入toggle功能相似的js文件,進行混合使用

2.可以合并生命周期

//mixinconst hi = { mounted() {  console.log('this mixin!') }}//vue組件new Vue({ el: '#app', mixins: [hi], mounted() {  console.log('this Vue instance!') }});//Output in console> this mixin!> this Vue instance!

先輸出的是mixins的數據

3、可以全局混合(類似已filter)

Vue.mixin({ mounted() {  console.log('hello from mixin!') }, method:{   test:function(){   }  }})new Vue({ el: '#app', mounted() {  console.log('this Vue instance!') }})

會在每一個組件中答應周期中的log,同時里面的方法,類似于vue的prototype添加實例方法一樣。

var install = function (Vue, options) { // 1. 添加全局方法或屬性 Vue.myGlobalMethod = function () {  // 邏輯... } // 2. 添加全局資源 Vue.directive('my-directive', {  bind (el, binding, vnode, oldVnode) {   // 邏輯...  }  ... }) // 3. 注入組件 Vue.mixin({  created: function () {   // 邏輯...  }  ... }) // 4. 添加實例方法 Vue.prototype.$myMethod = function (options) {  // 邏輯... }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 曲水县| 鄂尔多斯市| 神池县| 铁力市| 涞源县| 喀喇沁旗| 芷江| 陈巴尔虎旗| 巴楚县| 洞口县| 安义县| 泰和县| 积石山| 若尔盖县| 阿克| 中方县| 汝城县| 赣州市| 保康县| 海门市| 腾冲县| 叙永县| 合山市| 彭山县| 应用必备| 浏阳市| 临安市| 上思县| 祁门县| 广昌县| 玉门市| 台湾省| 云龙县| 三原县| 乐陵市| 池州市| 淳化县| 临安市| 岱山县| 高唐县| 财经|