ベテランドライバー読書ノート——Vue学習ノート

21904 ワード

Vue学習ノート
この記事では、次の内容を参照してください.
  • iOS開発視点Vue学習に必要ないくつかの知識点
  • Vueインスタンス構造
    var vm = new Vue({
      //    
      el: '#example',
      //  
      data: {
        message: 'Hello'
      },
      //    
      computed: {
        fullName: {
            // getter
            get: function () {
                return this.firstName + ' ' + this.lastName
            },
            // setter
            set: function (newValue) {
                var names = newValue.split(' ')
                this.firstName = names[0]
                this.lastName = names[names.length - 1]
            }
        }
      },
      //    
      watch: {
        //    `question`     ,        
        question: function (newQuestion, oldQuestion) {
          this.answer = 'Waiting for you to stop typing...'
          this.getAnswer()
        }
      },
      //    
      methods: {
        reversedMessage: function () {
            return this.message.split('').reverse().join('')
        }
      }
    })
    

    Vueリスニングインスタンス

    Ask a yes/no question:

    {{ answer }}

    var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!' }, watch: { // `question` , question: function (newQuestion, oldQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // `_.debounce` Lodash 。 // , yesno.wtf/api // AJAX 。 // `_.debounce` ( `_.throttle`) , // :https://lodash.com/docs#debounce getAnswer: _.debounce( function () { if (this.question.indexOf('?') === -1) { this.answer = 'Questions usually contain a question mark. ;-)' return } this.answer = 'Thinking...' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 500 ) } })

    Vueインスタンスのライフサイクル
    beforeCreate->created->beforeMount->mounted->beforeUpdate->updated->beforeDestroy->destryed
    v-bind
    バインドラベルフィールドとVueの対応関係
    
    ...
    
    
    ...
    

    v-on
    バインディングイベントとVueの対応関係
    
    ...
    
    
    ...
    

    Vueコンポーネント
    Vue.component('my-component', {
      template: '

    Hi

    ' })

    Classバインド
    通常

    数组

    HTML:
    
    JS: data: { activeClass: 'active', errorClass: 'text-danger' }

    条件


    Style绑定

    HTML:
    
    JS: data: { styleObject: { color: 'red', fontSize: '13px' } }

    v-if

    
    
    

    表示するかどうかについては、v-showも同じ効果を得ることができますが、違いは
    v-showの要素は常にレンダリングされ、DOMに保持されます.v-showは要素のCSS属性displayを簡単に切り替えるだけです.
    v-showは要素もv-elseもサポートしていません.
    v-ifとv-show
    v-ifは、切替中に条件ブロック内のイベントリスナーとサブコンポーネントが適切に破棄され、再構築されることを保証するため、「真」の条件レンダリングです.
    v-ifも不活性です.初期レンダリング時に条件が偽の場合、条件が初めて真になるまで条件ブロックのレンダリングが開始されません.
    それに比べて、v-showはずっと簡単です.初期条件が何であれ、要素は常にレンダリングされ、CSSに基づいて簡単に切り替えるだけです.
    一般に、v-ifはより高いスイッチングオーバーヘッドを有し、v-showはより高い初期レンダリングオーバーヘッドを有する.したがって、非常に頻繁に切り替える必要がある場合は、v-showを用いるのが好ましい.実行時に条件が変更されない場合は、v-ifを使用するとよい.
    v-for
    HTML:
    
    • {{ parentMessage }} - {{ index }} - {{ item.message }}
    JS: var example2 = new Vue({ el: '#example-2', data: { parentMessage: 'Parent', items: [ { message: 'Foo' }, { message: 'Bar' } ] } })

    オブジェクトに対してもv-for構文を使用できます.
    HTML:
    
    {{ index }}. {{ key }}: {{ value }}
    JS: new Vue({ el: '#v-for-object', data: { object: { firstName: 'John', lastName: 'Doe', age: 30 } } })

    v−forがv−ifと併用される場合、forサイクルにif判定を追加することに相当する.
    2.2.0+のバージョンでは、コンポーネントでv-forを使用する場合、keyが必要になります.eg.:
    
    

    TODO LISTの完成例
    HTML:
    
    JS: Vue.component('todo-item', { template: '\
  • \ {{ title }}\ \
  • \ ', props: ['title'] }) new Vue({ el: '#todo-list-example', data: { newTodoText: '', todos: [ { id: 1, title: 'Do the dishes', }, { id: 2, title: 'Take out the trash', }, { id: 3, title: 'Mow the lawn' } ], nextTodoId: 4 }, methods: { addNewTodo: function () { this.todos.push({ id: this.nextTodoId++, title: this.newTodoText }) this.newTodoText = '' } } })

    配列について
    Vueは配列に多くの変異法を提供し,配列の変化を観察しながら更新を試みた.
  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

  • また、Vueは、元の配列の値を変更することなく、新しい配列を返す非変異的な方法も提供しています.
  • filter()
  • concat()
  • slice()

  • 使用上、古い配列を新しい配列で置き換えることができ、Vue内部を最適化し、レンダリング効率を向上させます.
    注目すべきは、JavaScriptの制限により、Vueは以下の変動の配列を検出できないことです.
    インデックスを使用して直接アイテムを設定する場合、例えばvm.items[indexOfItem]=newValue配列の長さを変更すると、たとえばvm.items.length = newLength
    1つ目の問題に対処するには、次の3つの方法を使用します.
    // Vue.set
    Vue.set(vm.items, indexOfItem, newValue)
    // Array.prototype.splice
    vm.items.splice(indexOfItem, 1, newValue)
    // Vue.set     
    vm.$set(vm.items, indexOfItem, newValue)
    

    2つ目の問題解決策:
    vm.items.splice(newLength)
    

    配列だけでなく、オブジェクトにもVueで検出できない変化があります.
    Vueはオブジェクト属性の追加または削除を検出できません
    この問題を解決するために、私は次の関数を呼び出すことができます.
    追加
    Vue.set(vm.userProfile, 'age', 27)
    vm.$set(vm.userProfile, 'age', 27)
    

    複数の値を追加する場合は、新しいオブジェクトを使用してオブジェクトを置換します.
    vm.userProfile = Object.assign({}, vm.userProfile, {
      age: 27,
      favoriteColor: 'Vue Green'
    })
    

    Vueでのイベントバインドについて
    v-onは、イベントにコールバックをバインドするために使用できます.コールバックは式です.
    HTML:
    

    The button above has been clicked {{ counter }} times.

    JS: var example1 = new Vue({ el: '#example-1', data: { counter: 0 } })

    同様に、次の方法があります.
    HTML:
    
    JS: var example2 = new Vue({ el: '#example-2', data: { name: 'Vue.js' }, // `methods` methods: { greet: function (event) { // `this` Vue alert('Hello ' + this.name + '!') // `event` DOM if (event) { alert(event.target.tagName) } } } })

    またgreetメソッドはJS情勢で直接呼び出すことができる.
    example2.greet()
    

    この機能により、イベントバインドにはもう1つの変形があります.
    HTML:
    
    JS: new Vue({ el: '#example-3', methods: { say: function (message) { alert(message) } } })

    さらに、Vueはv-onに一連のイベント修飾子を提供し、イベントの転送をカスタマイズします.
    
    
    
    
    
    ...
    ...
    ...

    按键修饰符

    • .enter
    • .tab
    • .delete (捕获“删除”和“退格”键)
    • .esc
    • .space
    • .up
    • .down
    • .left
    • .right
    
    
    

    v-model
    入力ボックス
    HTML:
    
    Multiline message is:

    {{ message }}