七、vue語法補充二(動態組件 & 異步組件、訪問元素 & 組件、混入)


1、.sync 修飾符

  2.3.0+ 新增

  vue 修飾符sync的功能是:當一個子組件改變了一個 prop 的值時,這個變化也會同步到父組件中所綁定。類似於v-model的效果

  例子:

this.$emit('update:title', newTitle)

然后父組件可以監聽那個事件並根據需要更新一個本地的數據屬性

<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>

使用.sync 修飾符代替

<text-document v-bind:title.sync="doc.title"></text-document>

https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6

2、keep-alive

  <keep-alive>是Vue的內置組件,能在組件切換過程中將狀態保留在內存中,防止重復渲染DOM

<!-- 失活的組件將會被緩存!-->
<keep-alive>
  <component v-bind:is="currentTabComponent"></component>
</keep-alive>

https://cn.vuejs.org/v2/api/#keep-alive

3、異步組件

  只在需要的時候才從服務器加載一個模塊。Vue 允許你以一個工廠函數的方式定義你的組件,這個工廠函數會異步解析你的組件定義

new Vue({
  // ...
  components: {
    'my-component': () => import('./my-async-component')
  }
})

  require.ensure()實現按需加載

4、處理邊界情況

  1.訪問根實例:在每個 new Vue 實例的子組件中,其根實例可以通過 $root 屬性進行訪問

// 獲取根組件的數據
this.$root.foo

   很少用,應為一般使用Vuex 來管理應用的狀態

  2.訪問子組件實例或子元素:通過 ref 特性為這個子組件賦予一個 ID 引用

<input ref="input">
methods: {
  // 用來從父級組件聚焦輸入框
  focus: function () {
    this.$refs.input.focus()
  }
}

  3.依賴注入:

    實例選項:provide 和 inject

provide: function () {
  return {
    getMap: this.getMap
  }
}
inject: ['getMap']

5、混入 (mixins)

  混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被混入該組件本身的選項。

// 定義一個混入對象
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}

// 定義一個使用混入對象的組件
var Component = Vue.extend({
  mixins: [myMixin]
})

var component = new Component() // => "hello from mixin!"

  https://cn.vuejs.org/v2/guide/mixins.html

6、Vue.set( target, key, value )向響應式對象中添加一個屬性

  • 參數:

    • {Object | Array} target
    • {string | number} key
    • {any} value
  • 返回值:設置的值。

  • 用法:

    向響應式對象中添加一個屬性,並確保這個新屬性同樣是響應式的,且觸發視圖更新。它必須用於向響應式對象上添加新屬性,因為 Vue 無法探測普通的新增屬性 (比如 this.myObject.newProperty = 'hi')

7、(轉)vue項目的一些心得


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM