一、 準備工作
1. 初始化項目
webpack模板已經配置好了webpack.config所以less less-loader不需要重新配置。
vue init webpack itany
cd itany
cnpm install
cnpm install less less-loader -D
cnpm install vuex axios -S
npm run dev
2. 項目資源
清除原來的樣式
數據
|-reset.css
|-data.json
3. 創建目錄結構
首先清除項目中的部分內容
創建如下目錄結構:
|-data.json
|-static
|-css
|-reset.css
4. 配置API接口,模擬後臺數據
在新版的webpack模板中,沒有dev.srver.js取而代之的是webpack.dev.config.js
配置方式可參考:https://blog.csdn.net/yusirxiaer/article/details/79602466
使用express框架啓動一個Node服務器,配置API接口,模擬後臺數據
測試API:
http://localhost:8080/api/seller
http://localhost:8080/api/goods
http://localhost:8080/api/ratings
二、項目整體結構開發
2.1建立store文件的相關內容,並在main.js裏面引入註冊
在store下的index.js裏面,需要引入vue ,vuex
2.2新建組件header,並在header裏面訪問api/seller下的數據
首先在store下的seller模塊actions下添加請求方法
需要在此模塊下導入axios模塊,因爲不是組件,不能像添加原型方法那樣使用axios,只能導入
getSeller({commit,state}){
axios.get('/api/seller').then(resp=>{
console.log(resp)
})
}
然後header編輯,組件發出請求
export default {
created(){
this.$store.dispatch('getSeller');
},
}
import {mapGetters} from 'vuex'
export default {
created(){
this.$store.dispatch('getSeller');
},
computed:{
//對象展開運算符
...mapGetters([
'seller'
]),
msg(){
return 'i love animals'
}
}
}
const state={
seller:{}
}
const getters={
seller(state){
return state.seller;
}
}
const actions={
getSeller({commit,state}){
axios.get('/api/seller').then(resp=>{
// console.log(resp);
// state.seller=resp.data.data;
// if(resp.data.errno==0){
// //commit同樣也可以提交數據
commit(types.GET_SELLER,resp.data.data);
// }
})
}
}
const mutations={
//第一個參數是state對象,第二個參數commit過來的數據
[types.GET_SELLER](state,data){
state.seller=data;
}
}