vue採坑指南
阿新 • • 發佈:2018-11-05
- 入門時,一直不清楚 new Vue 和 Vue.component 選項的區別
new Vue 建立的是根例項
new Vue({
el : '#app',
data(){}
})
Vue.component 建立的是元件
Vue.component('button-counter',{
data(){}
})
因為元件是可複用的 Vue 例項,所以它們與 new Vue 接收相同的選項,例如 data、computed、watch、methods 以及生命週期鉤子等。僅有的例外是像 el 這樣根例項特有的選項。
- 生命週期
beforeCreate/created beforeMount/mounted
beforeUpdate/updated beforeDestroy/destroyed - render優先順序
render函式>template模板>outer HTML - 元件基本用法
<div id="app">
</div>
Vue.component()定義全域性元件
new Vue({ el : '#app' })在每個頁面生成一個容器元件
-
單檔案元件
什麼,你說上面這種寫法和你專案中的不一樣,是下面這樣的,噢,那你說的是單檔案元件(.vue)
https://cn.vuejs.org/v2/guide/single-file-components.html<template></template> <script></script> <style></style>
對,這就是單檔案元件,江湖人稱 Single-File Components (SFCs),關注點分離並不代表型別分離(此話抄自vue官網),模板邏輯樣式是內部耦合的
<template> <div class="example">{{ msg }}</div> </template> <script> </script> export default { data () { return { msg: 'Hello World' } } ... } <style lang="less" scoped> .example { color: red; } </style>
-
指令
指令帶有字首 v-,以表示它們是 Vue 提供的特殊特性,如v-bind、v-modal、v-on等 -
計算屬性
computed計算屬性是基於依賴進行快取,依賴不變,不會重新求值。而
methods呼叫方法,都會重新計算。
{{reversedMessage}}
...
computed: {
reversedMessage: function () { // 計算屬性的 getter
return this.message.split('').reverse().join('')
}
}
- v-if v-else
用key管理可複用的元素 - v-show 與 v-if 的不同
v-show與v-if都能控制元素的展示,不同的是帶有 v-show 的元素始終會被渲染並保留在 DOM 中。v-show 只是簡單地切換元素的 CSS 屬性 display。
一般來說,v-if 有更高的切換開銷,而 v-show 有更高的初始渲染開銷。因此,如果需要非常頻繁地切換,則使用 v-show 較好;如果在執行時條件很少改變,則使用 v-if 較好。 - 全域性註冊/區域性註冊
// 全域性註冊,用Vue.component註冊的
Vue.component("blog-post",{});
// 區域性註冊,用js物件定義元件,然後在components中引用
var blogPost = { /* ... */ };
var app = new Vue({
el: '#app',
components: {
blogPost
}
}}
- 靜態/動態prop
// 靜態,直接傳值
<blog-post title="My journey with Vue"></blog-post>
// 動態
<blog-post :title="title"></blog-post>
vue是單項資料流,同通過prop傳遞,子元件不應該更改prop,
如要更改,通常有兩種情況:
props: [initialCounter, size],
data(){
return {
counter: this.initialCounter // 情況一,data,作為初始值
}
},
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase(); // 情況二,computed,定義計算屬性
}
}
- 作用域插槽
父元件模板的所有東西都會在父級作用域內編譯;子元件模板的所有東西都會在子級作用域內編譯。
slot-scope - 非同步元件
vue允許以工廠函式的方式定義元件,元件被渲染時,工廠函式才會觸發
和webpack的code-splitting配合使用https://cn.vuejs.org/v2/guide/components-dynamic-async.html
Vue.component('async-webpack', resolve=> require(['./my-async-component'], resolve))
// 這個特殊的 `require` 語法將會告訴 webpack,自動將你的構建程式碼切割成多個包,這些包會通過 Ajax 請求載入
})
也可以在工廠函式中返回一個Promise
Vue.component('async-webpack', () => import('./my-async-component'))
// 這個 `import` 函式會返回一個 `Promise` 物件。
當使用區域性註冊的時候,你也可以直接提供一個返回 Promise 的函式:
new Vue({
...
components: {
"my-component" : ()=>import('./my-component')
}
})