初步學習Vue

​ 以前用vue2寫過一些cms系統,簡單的數據處理,基本的組件都寫過,可是最近一年使用React比較多,vue項目很久沒寫,並且據說vue3也已經出來了,因此從新複習一下,將vue的知識點概括概括,方便往後使用和查找。css

​ 學習基於vue官方文檔,如今簡單的將文檔過一遍,簡單的記錄一下知識html

1.建立應用實例
Vue.createApp({ /* 選項 */ })

建立根組件:createApp(App).mount('#app')
2.生命鉤子
  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeUnmounted
  • unmounted
3.模版語法

文本插值vue

<span v-once>這個將不會改變: {{ msg }}</span> 
// v-once指令當數據改變時,插值處的內容不會更新

原始HTMLapi

v-html能將html輸出,雙大括號只會將內容輸入爲文本瀏覽器

<p>Using mustaches: {{ rawHtml }}</p>
<p>Using v-html directive: <span v-html="rawHtml"></span></p>
 //rawHtml: '<span style="color: red">This should be red.</span>'

Attribute緩存

v-bind指令可使數據在HTML attribute中使用app

參數和動態參數異步

<a v-bind:href="url"> ... </a> // <a :href="url"> ... </a>
<a v-on:click="doSomething"> ... </a> // <a @click="doSomething"> ... </a>
<a v-bind:[attributeName]="url"> ... </a>

Vue 自動爲 methods 綁定 this,以便於它始終指向組件實例。這將確保方法在用做事件監聽或回調時保持正確的 this 指向。在定義 methods 時應避免使用箭頭函數,由於這會阻止 Vue 綁定恰當的 this 指向。函數

4.computed和watch(計算屬性和監聽器)

計算屬性是基於它們的反應依賴關係緩存的。計算屬性只在相關響應式依賴發生改變時它們纔會從新求值。post

計算屬性默認只有 getter,不過在須要時你也能夠提供一個 setter

watch 選項提供了一個更通用的方法,來響應數據的變化。當須要在數據變化時執行異步或開銷較大的操做時,這個方式是最有用的。

5.class屬性
<div :class="[isActive ? activeClass : '', errorClass]"></div>
<div :class="[{ active: isActive }, errorClass]"></div>
<div :class="{ active: isActive }"></div>
6.v-if和v-show的區別

v-if是真正的條件渲染,會確保在切換過程當中條件塊內的事件監聽器和子組件適當地被銷燬和重建。它的渲染是惰性的,初始渲染時條件爲假,直到條件第一次變爲真,開始渲染塊

v-show是元素渲染,只是單純的基於css進行切換

v-if 有更高的切換開銷,而 v-show 有更高的初始渲染開銷。所以,若是須要很是頻繁地切換,則使用 v-show 較好;若是在運行時條件不多改變,則使用 v-if 較好。

7.v-for
<ul id="array-with-index">
  <li v-for="(item, index) in items"> // for in 和 for of
    {{ parentMessage }} - {{ index }} - {{ item.message }}
  </li>
</ul>
8.is & v-is
<component :is="currentTabComponent"></component>
<table>
  <tr v-is="'blog-post-row'"></tr> // 這裏至關於使用blog-post-row組件
</table>

HTML 屬性名不區分大小寫,所以瀏覽器將把全部大寫字符解釋爲小寫。這意味着當你在 DOM 模板中使用時,駝峯 prop 名稱和 event 處理器參數須要使用它們的 kebab-cased (橫線字符分隔) 等效值

9.自定義修飾符

添加到組件 v-model 的修飾符將經過 modelModifiers prop 提供給組件

<div id="app">
  <my-component v-model.capitalize="myText"></my-component>
  {{ myText }}
</div>

const app = Vue.createApp({
  data() {
    return {
      myText: ''
    }
  }
})

app.component('my-component', {
  props: {
    modelValue: String,
    modelModifiers: {
      default: () => ({})
    }
  },
  methods: {
    emitValue(e) {
      let value = e.target.value
      if (this.modelModifiers.capitalize) {
        value = value.charAt(0).toUpperCase() + value.slice(1)
      }
      this.$emit('update:modelValue', value)
    }
  },
  template: `<input
    type="text"
    :value="modelValue"
    @input="emitValue">`
})

app.mount('#app')
相關文章
相關標籤/搜索