(1) 當(dāng)跨域請求報錯 Access-Control-Allow-Origin 訪問控制允許同源,有兩種辦法解決開發(fā)環(huán)境下的跨域問題 ( 注意 : 只是開發(fā)環(huán)境,只是為了方便調(diào)試 ),用 cors ( Cross-origin resource sharing ) 跨域資源共享,解決實際生產(chǎn)中的跨域問題。
- 開發(fā)環(huán)境的跨域:(以下有兩種方法)
(1) 下載瀏覽器插件 allow control allow origin
使用 Allow-Control-Allow-Origin: *,默認會修改所有 response,修改 response header 允許跨域資源訪問
(2) proxyTable
vue-cli的config文件中的index.js文件里有一個參數(shù)叫proxyTable
( proxy是代理的意思 )
作用:1.將復(fù)雜的url簡化。2.跨域
項目根目錄/config/index.js
proxyTable: { // proxy是代理的意思
'/api': { // 用 ( /api ) 代替 ( http://localhost:3000/api )
target: 'http://localhost:3000/', // 接口域名
changeOrigin: true, // 是否跨域
pathRewrite: { // 路徑重寫,一般不變
'^/api': ''
}
}
}
請求到 /api/users 現(xiàn)在會被代理到請求 http://localhost:3000/api/users。
--------------------------------------------------------------------------------
具體請求時:
_getDistList() {
this.$http.get('/api/路由地址')
.then((response) => {
console.log(response)
})
}
- 真實環(huán)境的跨域:(cors跨域資源共享)
cors實在服務(wù)器端配置,需要服務(wù)器和瀏覽器同時支持才可以。
cors跨域,只是在服務(wù)器端配置,前端請求就和平時同源的請求一樣,基本不變。
cors可以發(fā)送get和post請求,jsonp只能發(fā)送get請求
(2) jsonp跨域
(3) 后端代理
(4) watch 觀察者
- 當(dāng)你想要在數(shù)據(jù)變化響應(yīng)時,執(zhí)行異步操作或開銷較大的操作,使用watch
- 觀察數(shù)據(jù)變化,在被觀察的數(shù)據(jù)變化時,執(zhí)行需要執(zhí)行的異步方法函數(shù),和mobx中的observer相似
watch: {
data() {
setTimeout(() => {
this.refresh() // 當(dāng)data變化是,更新better-scroll
}, this.refreshDelay)
}
}
(5) vue-lazyload 懶加載插件
- 安裝
cnpm install vue-lazyload --save
- 使用
在main.js中
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, { }) // 所有的第三方插件都要Vue.use()
- 實例
main.js
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
loading: require('common/image/logo2.png') //加載過程中替換的圖片
})
--------------------------------------------------------------
recommend.vue
<div class="icon">
<img v-on:load="loadImage" v-lazy="item.coverImgUrl" alt="圖片" width="60" height="60">
</div>
(6) fastclick 和 better-scroll的點擊沖突
- 回憶fastclick的用法
在main.js中
import fastclick from 'fastclick' // 解決移動端點擊300ms延遲
fastclick.attach(document.body) // attach是關(guān)聯(lián)的意思
解決方案:
<div class="icon">
<img v-on:load="loadImage"
v-lazy="item.coverImgUrl"
class="needsclick" // 設(shè)置class為needsclick
alt="圖片"
width="60"
height="60"
>
</div>
(7) forEach() 和 .map() 和 push
forEach()
- array.forEach(function(currentValue, index, array), thisValue)
currentValue : 必需。當(dāng)前元素
index : 可選。當(dāng)前元素的索引值。
arr : 可選。當(dāng)前元素所屬的數(shù)組對象。
.map()
- map:map即是 “映射”的意思 用法與 forEach 相似
- 返回值 : 一個新數(shù)組,每個元素都是回調(diào)函數(shù)的結(jié)果。
let array = arr.map(function callback(currentValue, index, array) {
// Return element for new_array
}[, thisArg])
push()
- push() 方法可向數(shù)組的末尾添加一個或多個元素,并返回新的長度。
arrayObject.push(newelement1,newelement2,....,newelementX)
newelement1 : 必需。要添加到數(shù)組的第一個元素。
newelement2 : 可選。要添加到數(shù)組的第二個元素。
newelementX : 可選??商砑佣鄠€元素。
forEach()
array.forEach(function(currentValue, index, arr), thisValue)
var arr = [1,2,3,4];
arr.forEach(function(value,index,array){
array[index] == value; //結(jié)果為true
sum+=value;
});
console.log(sum); //結(jié)果為 10
---------------------------------------------------------------------------
list.forEach((item, index) => {
if (index < HOT_SINGER_LEN) { // 如果index<10
map.hot.items.push(new Singer(
{
id: item.Fsinger_mid,
name: item.Fsinger_name
}
))
}
}
-----------------------------------------------------------------------------
完整案列:
<template>
<div class="rank" ref="rank">
<div v-for="m in aa" v-if="aa.length">
{{m.name}}
</div>
這是排行頁面
</div>
</template>
<script type="text/ecmascript-6">
export default {
data() {
return {
aa: [],
bb: [
{a: '10', b: '20', c: '30'},
{a: '校長', b: '學(xué)生', c: '老師'},
{a: '領(lǐng)導(dǎo)', b: '職員', c: '老板'}
]
}
},
created() {
this.getData()
},
methods: {
getData() {
this.bb.forEach((value, index) => {
this.aa.push({
id: value.a,
name: value.b,
key: index
})
})
console.log(this.aa)
}
}
}
</script>
// 輸出結(jié)果為:20 學(xué)生 職員
(8)
$emit 派發(fā)事件,分發(fā)事件;
$on監(jiān)聽事件;
$off取消監(jiān)聽;
- Event.$emit(‘msg‘,this.msg) 發(fā)送數(shù)據(jù)
第一個參數(shù)是派發(fā)的事件的名稱,接收時還用這個名字接收;
第二個參數(shù)是這個數(shù)據(jù)現(xiàn)在的位置; - 通過vm.$emit( event, […args] )函數(shù) : 可以讓父組件知道子組件調(diào)用了什么函數(shù)
listview.vue ( 子組件 )
<ul>
<li v-for="group in data" class="list-group" ref="listGroup">
<h2 class="list-group-title">{{group.title}}</h2>
<uL>
<li @click="selectItem(item)" v-for="item in group.items" class="list-group-item">
<img class="avatar" v-lazy="item.avatar">
<span class="name">{{item.name}}</span>
</li>
</uL>
</li>
</ul>
methods: {
selectItem(item) {
this.$emit('select', item) // 派發(fā)事件,參數(shù)是item,讓外界知道是點擊了哪個元素
}
}
// 像下面的寫法,直接在listview中寫邏輯,也能達到同樣的效果
// 因為listview是基礎(chǔ)組件,不做邏輯部分。所以最好派發(fā)出事件,像上面那樣
methods: {
selectItem(item) {
this.$router.push({
path: `/singer/${item.id}`
})
},
----------------------------------------------------------------------------------
singer.vue ( 父組件 )
<template>
<div class="singer" ref="singer">
<Listview v-on:select="selectSinger()" v-bind:data="singers"></Listview>
// 接收select事件,selectSinger()做什么事
<router-view></router-view>
</div>
</template>
selectSinger(singer) { // 子組件派發(fā)的this.$emit('select',item),這個item就是singer
this.$router.push({ // this.$router.push() 路由跳轉(zhuǎn)
path: `/singer/${singer.id}`
})
},
或者:
methods: {
selectSinger(singer) { // 子組件派發(fā)的this.$emit('select',item),這個item就是singer
this.$router.push(`/singer/${singer.id}`)
},
(9)
嵌套路由
子路由 children[ { path: ':id', component: xxxxx } ]
路由跳轉(zhuǎn):this.$router.push({ path: xxxxx})
路由跳轉(zhuǎn)的另一種寫法: this.$router.push('xxxxxx')
router/index.js
export default new Router({
routes: [
{path: '/', name: 'home', redirect: '/recommend'},
{path: '/recommend', name: 'recommend', component: Recommend},
{
path: '/singer',
name: 'singer',
component: Singer,
children: [{
path: ':id',
component: SingerDetail
}]
},
{path: '/rank', name: 'rank', component: Rank},
{path: '/search', name: 'search', component: Search}
]
})
------------------------------------------------------------------------------
singer.vue
<template>
<div class="singer" ref="singer">
<Listview v-bind:data="singers"></Listview>
<router-view></router-view>
</div>
</template>
(10) axios請求的抽象,promise封裝
test.js
import axios from 'axios'
export function getImageUrl() {
return axios.get('http://image.baidu.com/channel/listjson?pn=15&rn=30&ie=utf8')
.then((response) => {
return Promise.resolve(response)
})
}
---------------------------------------------------------------------------
singer-detail.vue 中調(diào)用
import {getImageUrl} from 'api/test.js'
export default {
created() {
this.getD()
},
methods: {
getD() {
getImageUrl().then((data) => {
console.log(data.data.data)
})
}
}
}
(10) 傳統(tǒng)的傳值,從singer頁跳轉(zhuǎn)到singer-detail中
步驟:
- (1) 在listview基礎(chǔ)組件中,在v-for循環(huán)的dom上綁定事件,這個事件中有派發(fā)事件函數(shù)this.$emit('select', item)
listview.vue
<li @click="selectItem(item)" v-for="item in group.items" class="list-group-item">
methods: {
selectItem(item) {
this.$emit('select', item) //點擊的tiem數(shù)據(jù)作為參數(shù)
}
}
- (2) 在 (父組件singer組件) 中接收 (listview子組件) 派發(fā)過來的事件,并執(zhí)行新的事件selectSinger,跳轉(zhuǎn)路由地址,頁面跳轉(zhuǎn)到detail組件。即router-view顯示的頁面,并且把singer存入data的fromListData中,fromListData作為數(shù)據(jù)傳入detail組件。
singer.vue
<Listview v-on:select="selectSinger" v-bind:data="singers"></Listview>
<router-view v-bind:dataFromListToDetail="fromListData"></router-view>
data() {
return {
singers: [],
fromListData: {}
}
},
methods: {
selectSinger(singer) { // 子組件派發(fā)的this.$emit('select',item),這個item就是singer
this.$router.push({
path: `/singer/${singer.id}`
})
this.fromListData = singer // 傳統(tǒng)的傳值方法,得到點擊的item的值dsinger
console.log(this.fromListData)
this.setSinger(singer)
},
- (3) detail組件接收singer組件傳過來的fromListData。并渲染
singer-detail.vue
<template>
<div class="singer-detail">
<ul>
<li>
<div class="bbb">
{{dataFromListToDetail.name}}
</div>
</li></ul>
</div>
</template>
<script type="text/ecmascript-6">
export default {
props: {
dataFromListToDetail: {
type: Object
}
}
}
</script>

(10) VUEX 狀態(tài)管理
(1) 每個vue的核心就是 Store倉庫
"store" 基本上就是一個容器,它包含著你的應(yīng)用中大部分的狀態(tài)(state)
(2) Vuex 和單純的全局對象的區(qū)別
(1) Vuex 的狀態(tài)存儲是響應(yīng)式的 :
當(dāng) Vue 組件從 store 中讀取狀態(tài)的時候,若 store 中的狀態(tài)發(fā)生變化,那么相應(yīng)的組件也會相應(yīng)地得到高效更新。
(2) 不能直接改變 store 中的狀態(tài)
-改變 store 中的狀態(tài)的唯一途徑就是顯式地提交(commit) mutations。
-這樣使得我們可以方便地跟蹤每一個狀態(tài)的變化,從而讓我們能夠?qū)崿F(xiàn)一些工具幫助我們更好地了解我們的應(yīng)用。
(3) 項目結(jié)構(gòu)
Vuex 并不限制你的代碼結(jié)構(gòu)。但是,它規(guī)定了一些需要遵守的規(guī)則:
1.應(yīng)用層級的狀態(tài)應(yīng)該集中到單個 store 對象中。
2.提交(commit) mutation 是更改狀態(tài)的唯一方法,并且這個過程是同步的。
3.異步邏輯都應(yīng)該封裝到 action 里面。
只要你遵守以上規(guī)則,如何組織代碼隨你便。如果你的 store 文件太大,只需將 action、mutation 和 getters 分割到單獨的文件。
對于大型應(yīng)用,我們會希望把 Vuex 相關(guān)代碼分割到模塊中。下面是項目結(jié)構(gòu)示例:

(4) 核心概念
(4.1) state
單一狀態(tài)樹 :每個應(yīng)用僅包含一個store實例
- Vuex 使用 單一狀態(tài)樹 —— 是的,用一個對象就包含了全部的應(yīng)用層級狀態(tài)。至此它便作為一個『唯一數(shù)據(jù)源(SSOT)』而存在。
- 這也意味著,每個應(yīng)用將僅僅包含一個 store 實例。
- 單一狀態(tài)樹讓我們能夠直接地定位任一特定的狀態(tài)片段,在調(diào)試的過程中也能輕易地取得整個當(dāng)前應(yīng)用狀態(tài)的快照。
在 Vue 組件中獲得 Vuex 狀態(tài) : 在組件的計算屬性compoted中返回某個狀態(tài)
// 創(chuàng)建一個 Counter 組件
const Counter = {
template: `<div>{{ count }}</div>`, // 模板
computed: {
count () {
return store.state.count
}
}
}
每當(dāng) store.state.count 變化的時候, 都會重新求取計算屬性,并且觸發(fā)更新相關(guān)聯(lián)的 DOM。
然而,這種模式導(dǎo)致組件依賴全局狀態(tài)單例。在模塊化的構(gòu)建系統(tǒng)中,在每個需要使用 state 的組件中需要頻繁地導(dǎo)入,并且在測試組件時需要模擬狀態(tài)。
uex 通過 store 選項,提供了一種機制將狀態(tài)從根組件『注入』到每一個子組件中(需調(diào)用 Vue.use(Vuex)):
const app = new Vue({
el: '#app',
// 把 store 對象提供給 “store” 選項,這可以把 store 的實例注入所有的子組件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
通過在根實例中注冊 store 選項,該 store 實例會注入到根組件下的所有子組件中,且子組件能通過 this.$store 訪問到。
更新下Counter 的實現(xiàn):
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState 輔助函數(shù)
當(dāng)一個組件需要獲取多個狀態(tài)時候,將這些狀態(tài)都聲明為計算屬性會有些重復(fù)和冗余。為了解決這個問題,我們可以使用 mapState 輔助函數(shù)幫助我們生成計算屬性,讓你少按幾次鍵:
// 在單獨構(gòu)建的版本中輔助函數(shù)為 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數(shù)可使代碼更簡練
count: state => state.count,
// 傳字符串參數(shù) 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
(4.2) Getters ( store 中的計算屬性 )
- Getters 接受 state 作為其第一個參數(shù):
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
- Getters 也可以接受其他 getters 作為第二個參數(shù):
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
`
mapGetters 輔助函數(shù)
mapGetters 輔助函數(shù)僅僅是將 store 中的 getters 映射到局部計算屬性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用對象展開運算符將 getters 混入 computed 對象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想將一個 getter 屬性另取一個名字,使用對象形式:
mapGetters({
// 映射 this.doneCount 為 store.getters.doneTodosCount
doneCount: 'doneTodosCount'
})
`
(4.3) Mutations ( Vuex 中的 mutations 非常類似于事件 )
- 更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation
- Vuex 中的 mutations 非常類似于事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調(diào)函數(shù) (handler)。這個回調(diào)函數(shù)就是我們實際進行狀態(tài)更改的地方,并且它會接受 state 作為第一個參數(shù):
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 變更狀態(tài)
state.count++
}
}
})
你不能直接調(diào)用一個 mutation handler。這個選項更像是事件注冊:“當(dāng)觸發(fā)一個類型為 increment 的 mutation 時,調(diào)用此函數(shù)?!币獑拘岩粋€ mutation handler,你需要以相應(yīng)的 type 調(diào)用 store.commit 方法:
store.commit('increment')
提交載荷(Payload) 相當(dāng)于另一個參數(shù)
- 你可以向 store.commit 傳入額外的參數(shù),即 mutation 的 載荷(payload):
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10) // 另一個參數(shù)
在大多數(shù)情況下,載荷應(yīng)該是一個對象,這樣可以包含多個字段并且記錄的 mutation 會更易讀:
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
- 提交 mutation 的另一種方式是直接使用包含 type 屬性的對象:
store.commit({
type: 'increment',
amount: 10
})
`
使用常量替代 Mutation 事件類型
- 使用常量替代 mutation 事件類型在各種 Flux 實現(xiàn)中是很常見的模式。這樣可以使 linter 之類的工具發(fā)揮作用,同時把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app 包含的 mutation 一目了然:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我們可以使用 ES2015 風(fēng)格的計算屬性命名功能來使用一個常量作為函數(shù)名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
`
在組件中提交 Mutations
- 你可以在組件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數(shù)將組件中的 methods 映射為 store.commit 調(diào)用(需要在根節(jié)點注入 store)。
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment' // 映射 this.increment() 為 this.$store.commit('increment')
]),
...mapMutations({
add: 'increment' // 映射 this.add() 為 this.$store.commit('increment')
})
}
}
(4.4) Actions
- Action 類似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接變更狀態(tài)。
Action 可以包含任意異步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action 函數(shù)接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調(diào)用 context.commit 提交一個 mutation,或者通過 context.state 和 context.getters 來獲取 state 和 getters。當(dāng)我們在之后介紹到 Modules 時,你就知道 context 對象為什么不是 store 實例本身了。
實踐中,我們會經(jīng)常用到 ES2015 的 參數(shù)解構(gòu) 來簡化代碼(特別是我們需要調(diào)用 commit 很多次的時候):
actions: {
increment ({ commit }) {
commit('increment')
}
}
分發(fā) Action
- Action 通過 store.dispatch 方法觸發(fā):
store.dispatch('increment')
// dispatch:是派遣,調(diào)度的意思
乍一眼看上去感覺多此一舉,我們直接分發(fā) mutation 豈不更方便?實際上并非如此,還記得 mutation 必須同步執(zhí)行這個限制么?Action 就不受約束!我們可以在 action 內(nèi)部執(zhí)行異步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
- Actions 支持同樣的載荷方式和對象方式進行分發(fā):
// 以載荷形式分發(fā)
store.dispatch('incrementAsync', {
amount: 10
})
// 以對象形式分發(fā)
store.dispatch({
type: 'incrementAsync',
amount: 10
})
(4.4) Modules
- 由于使用單一狀態(tài)樹,應(yīng)用的所有狀態(tài)會集中到一個比較大的對象。當(dāng)應(yīng)用變得非常復(fù)雜時,store 對象就有可能變得相當(dāng)臃腫。
為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)