【译】Vue Patterns



英文原版:learn-vuejs

中文翻譯: yoyoys

此頁面集結了許多有用的 Vue 實作模式、技術、技巧、以及有幫助的參考連結。

  • Vue 實作模式 (learn-vuejs) 中文版
    • 元件宣告
      • 單文件組件(Single File Component, SFC) - 最為常見
      • 字串樣板 (String Template) (或是 es6 樣板字面值 (Template Literal)))
      • 渲染函式 (Render Function)
      • JSX
      • vue-class-component (使用 es6 classes)
        • 參考連結
    • 元件條件渲染 (Component Conditional Rendering)
      • 指令 (Directives) (v-if / v-else / v-else-if / v-show)
      • JSX
    • 動態元件
    • 元件組合
      • 基本組合 (Basic Composition)
      • 繼承 (Extends)
      • 混入 (Mixins)
      • 預設插槽 (Slots (Default))
      • 具名插槽(Named Slots)
      • 作用域插槽 (Scoped Slots)
      • 渲染屬性 (Render Props)
    • 參數傳遞 (Passing Props)
    • 高優先元件 (Higher Order Component, HOC)
    • 相依注入 (Dependency injection)
      • 提供 與 注入 (Provide / Inject)
      • 注入裝飾器模式 (@Provide / @Inject Decorator)
    • 錯誤處理 (Handling Errors)
      • errorCaptured 事件
    • 生產力小技巧
    • 有用的連結
      • 組建間的溝通
      • 重構技巧
      • Vuex
      • Mobx
      • 不須渲染的元件 (Renderless Component)
      • 目錄結構
      • 小技巧
      • 專案範例
      • 不良示範 (反模式)
      • 影片與音訊課程
      • 付費課程
      • 其他資訊

元件宣告

單文件組件(Single File Component, SFC) - 最為常見







字串樣板 (String Template) (或是 es6 樣板字面值 (Template Literal))


Vue.component('my-btn', {
  template: `
    
  `,
  data() {
    return {
      text: 'Click me',
    };
  },
  methods: {
    handleClick() {
      console.log('clicked');
    },
  },
});

渲染函式 (Render Function)


Vue.component('my-btn', {
  data() {
    return {
      text: 'Click me',
    };
  },
  methods: {
    handleClick() {
      console.log('clicked');
    },
  },
  render(h) {
    return h('button', {
      attrs: {
        class: 'btn-primary'
      },
      on: {
        click: this.handleClick,
      },
    });
  },
});

JSX


Vue.component('my-btn', {
  data() {
    return {
      text: 'Click me',
    };
  },
  methods: {
    handleClick() {
      console.log('clicked');
    },
  },
  render() {
    return (
      
    );
  },
});

vue-class-component (使用 es6 classes)







參考連結

  • 7 Ways To Define A Component Template in VueJS

元件條件渲染 (Component Conditional Rendering)

指令 (Directives) (v-if / v-else / v-else-if / v-show)



v-if

只在 v-if 值為 true 時渲染

v-if 與 v-else

只在 v-if 值為 true 時渲染

只在 v-if 值為 false 時渲染

v-else-if
只在 `type` 等於 `A` 時渲染
只在 `type` 等於 `B` 時渲染
只在 `type` 等於 `C` 時渲染
只在 `type` 不等於>fmf `A` 或 `B` 或 `C` 時渲染
v-show

永遠都會渲染,但是只在 `v-show` 值為 true 時顯示

如果你需要同時在多個元素上面做條件式渲染,你可以在