使用vue.js開發時的一些坑

關於響應式

vue的雙向綁定是基於響應式來作的,即給一個Vue對象的屬性加上getter, setter方法,在這些方法中處理雙向綁定。但這種方式就會出現下面這些坑vue

vue的組件化寫法真心很差用

舉個例子,我寫了個svg-icon的基礎組件,相似以下:數組

<template>
  <svg viewBox="0 0 24 24"
       preserveAspectRatio="xMidYMid meet"
       fit
       :style="style">
    <g><path :d="path"/></g>
  </svg>
</template>

<script type="text/babel">
  import propsMixin from './props-mixin'
  export default {
    mixins: [propsMixin],
    props: {
      path: {
        type: String,
        default: ''
      }
    },
    computed: {
      style() {
        return {
          fill: 'currentcolor',
          verticalAlign: 'middle',
          width: this.size,
          height: this.size
        }
      }
    }
  }
</script>

而後我每一個icon都只須要傳入不一樣的路徑就能夠了,babel

<template>
  <svg-icon path="M15.41 7.41l-1.41-1.41-6 6 6 6 1.41-1.41-4.58-4.59z" :size="size"></svg-icon>
</template>

<script>
  import svgIcon from './svg-icon.vue'
  import propsMixin from './props-mixin'
  export default {
    mixins: [propsMixin],
    components: {
      svgIcon
    }
  }
</script>

然而這裏就有個問題了,這裏有個size屬性決定icon的大小,若是我用這種方式來寫,那麼我每一個icon裏面都須要聲明size這個props,而且在模板上聲明,我嘞個去。。。svg

對象響應式

Vue中的屬性若是是Object,或者是數組,數組中有Object,那麼這些Object最好在最開始就把全部須要用到的屬性都定義一遍,若是在運行中從新添加屬性,這個屬性並非響應式的,就不會實現雙向綁定,例如:組件化

const vm = new Vue({
    data: {
        a: {
            text: 'aaa'
        }
    }
})
vm.a.b = 'ccc'

這樣的狀況,a的b屬性不是響應式的,因此不會雙向綁定this

Date對象

對Date對象的操做不是響應式的雙向綁定

相關文章
相關標籤/搜索