Vue2入門(mén) 從0到1

安裝

開(kāi)箱即用(學(xué)習(xí)推薦,最好上手)

<!-- 開(kāi)發(fā)環(huán)境版本,包含了有幫助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- 生產(chǎn)環(huán)境版本,優(yōu)化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>

開(kāi)始使用

創(chuàng)建一個(gè)Vue實(shí)列

var App = new Vue({
  el: '#app', // 實(shí)列化dom的選擇器
  components: {}, // 組件注冊(cè)
  data: {}, // 數(shù)據(jù)
  methods: {} // 函數(shù)
})

生命周期

總共分為8個(gè)階段:創(chuàng)建前/后,掛載前/后,更新前/后,銷(xiāo)毀前/銷(xiāo)毀后。

掛載
beforeCreate(創(chuàng)建前)created(創(chuàng)建后)beforeMount(掛載前)mounted(掛載后)

更新(元素或組件的變更操作)
beforeUpdate(更新前)updated(更新后)

銷(xiāo)毀(銷(xiāo)毀相關(guān)屬性)
beforeDestroy(銷(xiāo)毀前)destroyed(銷(xiāo)毀后)

以上生命周期常用的最常用的是mounted(掛載后) 前置數(shù)據(jù)的獲取處理在這里,因載入前dom并沒(méi)有渲染到頁(yè)面上,我們需要操作dom時(shí)會(huì)獲取到undefined。

其次是destroyed(銷(xiāo)毀后)是saas中使用到的,用于組件中定時(shí)任務(wù)的清除。

數(shù)據(jù)綁定與渲染

1.{{xxx}}

模板寫(xiě)法
例子 <h3>{{ message }}</h3>

2.v-bind:xxx

綁定內(nèi)容到html屬性中
例子 <h3 v-bind:class="xxx"></h3>
簡(jiǎn)寫(xiě) <h3 :class="xxx"></h3>

3.v-model

雙向綁定
例子 <input v-model="xxx">

4.v-html

以html的形式在標(biāo)簽內(nèi)部渲染內(nèi)容
例子 <div v-html="xxx"></div>

5.v-show

是否顯示dom
例子 <div v-show="true||fasle"></div>

6.v-if,v-else

是否渲染dom
需要注意v-else永遠(yuǎn)跟隨前面一個(gè)v-if,并且不提供else if功能
例子 <div v-if="boolean"></div><div v-else></div>

7.v-for

列表渲染
例子 <li v-for="(item, index) in list" :key="唯一標(biāo)識(shí)"></li>

事件處理

事件綁定 v-on:xxx
例子 <button v-on:click="changeColor">切換顏色</button>
簡(jiǎn)寫(xiě) <button @click="changeColor">切換顏色</button>

事件綁定分為帶括號(hào)和不帶括號(hào),是否有括號(hào)對(duì)事件的影響是不同的,如下
<button @click="funcDemo">無(wú)括號(hào)</button>
<button @click="funcDemo($event)">有括號(hào)時(shí)傳入事件對(duì)象</button>
<button @click="funcDemo('arg1')">有括號(hào)傳參1</button>
<button @click="funcDemo('arg1', 'arg2')">有括號(hào)傳參2</button>
<button @click="funcDemoObj1({a:1,b:2,c:3})">傳入對(duì)象</button>
<button @click="funcDemoObj2({a:1,b:2,c:3})">傳入對(duì)象 解構(gòu)賦值</button>

當(dāng)參數(shù)傳入對(duì)象時(shí),會(huì)因?yàn)榻邮辗绞降牟煌淖儏?shù)格式,如下
funcDemoObj1(obj){} 接收整個(gè)對(duì)象
funcDemoObj2({a, b, d = 4}){}只接收對(duì)象中的a和b,并聲明一個(gè)包含默認(rèn)值的屬性

有意思的是時(shí)間函數(shù)不管是否傳入$event在函數(shù)中都可以通過(guò)event獲取事件對(duì)象

組件注冊(cè)

全局注冊(cè)
Vue.component('component-a', { /* ... */ })

局部注冊(cè)
定義組件 var ComponentA = { /* ... */ }
然后在 components 選項(xiàng)中定義你想要使用的組件,如:components: { ComponentA }

Html中引入 <component-a></component-a> 或者 <ComponentA></ComponentA>在模塊化開(kāi)發(fā)中當(dāng)組件不使用插槽時(shí)可直接作為自合閉標(biāo)簽來(lái)使用如<component-a/> 或者 <ComponentA/>。
其中全大寫(xiě)的寫(xiě)法,只能在模塊化開(kāi)發(fā)中使用,同時(shí)也推薦在模塊化開(kāi)發(fā)中使用,以便于我們能快速查找代碼位置與區(qū)分組件的來(lái)源?,F(xiàn)在項(xiàng)目中,我們自己封裝或者二次封裝的組件就是使用的這種風(fēng)格。

自定義組件

以下是一個(gè)公共基礎(chǔ)組件代碼的聲明

Vue.component('component-a', {
  props: ['title'],
  template: '<h3 @click="func">A Num:{{clickNum}} ------ {{title}} <slot></slot></h3>',
  data () {
    return {
      clickNum: 0
    }
  },
  watch: {
    clickNum: {
      handler(newV, oldV) {}
    }
  },
  // ...生命周期
  methods: { 
    func() {
      this.clickNum++
      this.$emit('callback', '組件A參數(shù)1', '組件A參數(shù)2')
    }
  }
})

在父組件中使用 <component-a title="xxx" ></component-a>

Props

父組件通過(guò)props向子組件傳遞數(shù)據(jù) 父組件中寫(xiě)法<component-a title=”xxx”/>
上面的基礎(chǔ)組件代碼中的寫(xiě)法是一個(gè)基礎(chǔ)寫(xiě)法,只包含了參數(shù)名稱(chēng)
更加復(fù)雜嚴(yán)謹(jǐn)?shù)膶?xiě)法如下:

props: {
  // 限制類(lèi)型
  a: Number,
  // 多個(gè)可能類(lèi)型
  b: [String, Number],
  // 必填
  c: {
    type: String,
    required: true
  },
  // 帶有默認(rèn)值
  d: {
    type: Number,
    default: 100
  },
  // 對(duì)象默認(rèn)值
  e: {
    type: Object,
    default() {
      return { message: 'hello' }
    }
  }
}

其中必填和默認(rèn)值這兩項(xiàng)不需要同時(shí)存在選擇其一即可
Props是單向數(shù)據(jù)流綁定,子組件中通過(guò)$emit調(diào)用父組件暴露給子組件的函數(shù)進(jìn)行參數(shù)傳遞修改。代碼如下:
父組件暴露函數(shù)給子組件:
<component-a title="xxx" @xxx=”()=>{}”></component-a>
子組件調(diào)用:
this.$emit('xxx')
this.$emit('xxx', ...參數(shù))

Template

是模板代碼書(shū)寫(xiě)位置,寫(xiě)法和html完全相同
當(dāng)使用模塊化開(kāi)發(fā)時(shí),此處代碼放到文件中的<template></template>標(biāo)簽中
<slot></slot>插槽:
子組件中需要的地方加入<slot></slot>即可在加入的位置渲染父組件調(diào)用子組件時(shí)在組件標(biāo)簽中寫(xiě)入的內(nèi)容。

Data

這里并不像之前的實(shí)列化Vue一樣是一個(gè)對(duì)象,組件中的data必須一個(gè)函數(shù),每個(gè)實(shí)列化的組件單獨(dú)維護(hù)一份被返回對(duì)象,因此我們可以再同一個(gè)頁(yè)面中多次引入一個(gè)相同的組件而不會(huì)相互影響

Watch

以下是一個(gè)簡(jiǎn)單的監(jiān)聽(tīng)器代碼結(jié)構(gòu):

watch: {
  xxx(newValue, oldValue) {}
}

也可以這么寫(xiě):

watch: {
  xxx: {
    // 是數(shù)據(jù)改變時(shí)觸發(fā)的函數(shù)
    handler(newValue, oldValue) {}
  }
}

xxx是要監(jiān)聽(tīng)的屬性名稱(chēng),如需監(jiān)聽(tīng)對(duì)象中的某個(gè)屬性寫(xiě)法為 'obj.xxx'字符串,如下:

watch: {
  'obj.xxx': {
    // 是數(shù)據(jù)改變時(shí)觸發(fā)的函數(shù)
    handler(newValue, oldValue) {}
  }
}
Methods

函數(shù)代碼位置,函數(shù)中的this指向當(dāng)前實(shí)列對(duì)象,因此可以再函數(shù)中通過(guò)this.xxx獲取所有當(dāng)前組件中的內(nèi)容

以下是包含上述內(nèi)容的dome

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="app">
      
      <h3>{{ message }}</h3>
      
      <input v-model="message" @change="funcDemo('change', message)" @focus="funcDemo('focus', message)">
      
      <h3 :class="color">顏色</h3>
      
      <div>
        <button v-on:click="changeColor">切換顏色</button>
        <br /><br />
        <button @click="funcDemo">無(wú)括號(hào)</button>
        <button @click="funcDemo($event)">傳入事件對(duì)象</button>
        <button @click="funcDemo('arg1')">傳參1</button>
        <button @click="funcDemo('arg1', 'arg2')">傳參2</button>
        <button @click="funcDemoObj1({a:1,b:2,c:3})">傳入對(duì)象</button>
        <button @click="funcDemoObj2({a:1,b:2,c:3})">傳入對(duì)象 解構(gòu)賦值</button>
        <br /><br />
      </div>
      
      <h3 v-html="html"></h3>
      
      <ul>
        <li v-for="(item, index) in list" :key="item">no:{{index}} val:{{item}}</li>
      </ul>
      
      <component-a title="組件1" @callback="funcDemo">插槽區(qū)域提示的內(nèi)容</component-a>
      <component-a title="組件2"></component-a>
      <component-b :a="3" b="字符串或者數(shù)字" c="必填項(xiàng)" d="改變默認(rèn)值" :e="{message: '改變對(duì)象默認(rèn)message的值'}"></component-b>
    </div>
    
  </body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  Vue.component('component-a', {
    props: ['title'],
    template: '<h3 @click="func">A Num:{{clickNum}} ------ {{title}} <slot></slot></h3>',
    data () {
      return {
        clickNum: 0,
      }
    },
    watch: {
      clickNum: {
        handler(newV, oldV) {
          console.log('clickNum oldV', oldV, 'clickNum newV', newV)
        }
      }
    },
    methods: { 
      func() {
        this.clickNum++
        this.$emit('callback', '組件A參數(shù)1', '組件A參數(shù)2')
      }
    }
  })
  
  var ComponentB = {
    props: {
      // 限制類(lèi)型
      a: Number,
      // 多個(gè)可能類(lèi)型
      b: [String, Number],
      // 必填
      c: {
        type: String,
        required: true
      },
      // 帶有默認(rèn)值
      d: {
         type: String,
         default: '默認(rèn)值'
      },
      // 對(duì)象默認(rèn)值
      e: {
        type: Object,
        // 對(duì)象或數(shù)組默認(rèn)值必須從一個(gè)工廠函數(shù)獲取
        default() {
          return { message: '對(duì)象中message' }
        }
      },
    },
    template: `<div>
      <h4>A:{{a}}</h4>
      <h4>B:{}</h4>
      <h4>C:{{c}}</h4>
      <h4>D:{u0z1t8os}</h4>
      <h4>E:{{e.message}}</h4>
    </div>`,
    data() {
      return {}
    }
  }
  
  var App = new Vue({
    el: '#app',
    components: {ComponentB},
    data: {
      color: 'red',
      message: 'Hello Vue!',
      html: '<span class="blue">這是一端藍(lán)色文字的html渲染</span>',
      list: ['a','b','c']
    },
    mounted() {
      console.log('mounted...')
    },
    methods: {
      changeColor() {
        if (this.color == 'blue') {
          this.color = 'red'
        } else {
          this.color = 'blue'
        }
      },
      funcDemo(arg1, arg2 = '默認(rèn)的值2') {
        console.log('參數(shù)1', arg1, '參數(shù)2', arg2)
      },
      funcDemoObj1(obj) {
        console.log('參數(shù)', obj)
      },
      funcDemoObj2({a, b, d = 4}) {
        console.log('參數(shù)a', a ,'參數(shù)b', b, '參數(shù)d', d)
      }
    }
  })
</script>
<style>
  .red {
    color: red;
  }
  .blue {
    color: blue;
  }
</style>

框架搭建整體流程

點(diǎn)擊下載步驟 1-7 配置完成的完整 Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、Vue2 1.1 模板語(yǔ)法 1.1.1 模板的理解 html 中包含了一些 JS 語(yǔ)法代碼,語(yǔ)法分為兩種,分別...
    Cola_Mr閱讀 806評(píng)論 0 1
  • 標(biāo)簽(空格分隔): 聽(tīng)課 一、vuejs及相關(guān)工具介紹 1.1 學(xué)習(xí)收獲 了解一個(gè)中度復(fù)雜規(guī)模的應(yīng)用開(kāi)發(fā) 掌握Vu...
    lvyweb閱讀 299評(píng)論 2 0
  • #vue2筆記 ##腳手架文件結(jié)構(gòu) ├──node_modules ├──public │├──favicon.i...
    Daydream_許多閱讀 503評(píng)論 0 0
  • 初識(shí)Vue2.0 想讓Vue工作,就必須創(chuàng)建一個(gè)Vue實(shí)例,且要傳入一個(gè)配置對(duì)象 vue容器里的代碼依然符合htm...
    Zindex閱讀 722評(píng)論 0 0
  • 前言 您將在本文當(dāng)中了解到,往網(wǎng)頁(yè)中添加數(shù)據(jù),從傳統(tǒng)的dom操作過(guò)渡到數(shù)據(jù)層操作,實(shí)現(xiàn)同一個(gè)目標(biāo),兩種不同的方式....
    itclanCoder閱讀 26,244評(píng)論 1 12

友情鏈接更多精彩內(nèi)容