0%

關注點分離

關注點分離是目前主流框架都會帶入的概念,框架會較為專注在資料處理上,而畫面會透過框架的方式進行渲染,關於這部分與 this 的運作也有很大的關係。

常見的原始作法

Image
註:紅框為畫面,綠框為輸入欄位

關注點分離作法

Image
註:紅框為畫面,綠框為輸入欄位,藍框為資料集

優點:

對於開發者在開發時不會把畫面的程式碼跟操作或是資料的程式碼混在一起,資料與畫面是拆分開的,管理上較為便利。

概念:

  • 畫面-HTML
  • 資料-JS data
  • 方法-JS function(協助畫面與資料溝通之間的橋樑)

物件方式建立元件,元件結構如下,

  • 資料
  • 方法、觸發器
  • 生命週期(初始化):進入畫面第一次會被觸發的方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
      const component = {
    //資料
    data: ["待辦事項一", "待辦事項二", "待辦事項三"],
    //事件觸發
    removeData(id) {
    // console.log(this);
    this.data.splice(id, 1);
    this.render();
    },
    //渲染方法(Vue.js會處理這部分)
    render() {
    const list = document.querySelector("ul");
    let str = "";
    this.data.forEach(function (item, index) {
    str += `<li>${item}<button type="button" class="btn" data-id="${index}">刪除</button></li>`;
    });
    list.innerHTML = str;
    const btns = document.querySelectorAll(".btn");
    btns.forEach((item) => {
    item.addEventListener("click", (e) => {
    // console.log(this);//使用箭頭函式讓 this 指向 component
    // 重點,移除項目是先移除資料,而不是直接移除 DOM
    this.removeData(e.target.dataset.id);
    });
    });
    },
    //生命週期
    init() {
    this.render();
    }
    };
    component.init();
    Codepen

學習來源:六角學院–Vue 3 實戰影音課程