最近開始著手學習 Vue,先大略的過了一遍官方文檔,跟著敲過一部分官方文檔中的 DEMO,然而還是不甚了了。在網上找到了一個入門的筆記應用,即便是入門級的應用,在學習途中依舊困難重重。特將學習作此筆記,方便今后回看,也希望能夠幫到剛開始學習 Vue 的女同學
附原作者 Github 鏈接:https://github.com/lichenbuliren/vuex-notes-app2
預期目標
筆記具備如下基本功能
1.新增
2.刪除
3.收藏
4.在全部筆記和收藏筆記間切換
5.在當前列表中進行搜索
賣家秀
買家秀
準備工作
1.新建項目
選個文件夾存放項目,這里我用的是 Git Bush 執行語句($ 符號是 Git Bush 中自帶的),你也可以使用命令行,一樣的
選擇項目存放位置
2.查看模塊(愛看不看)
查看一下全局安裝的模塊 npm list --depth=0 -global
查看全局安裝的模塊
3.創建項目
在命令行輸入 vue init webpack vuex-note 并做好設置,創建一個項目
這都什么鬼
4.簡單解釋一下各個配置都是干嘛的
5.安裝完后會有提示,我們接著按照提示走
先是 cd vuex-note 進入剛剛創建的 vue 項目文件夾
安裝完成
再通過 npm run dev 跑起項目
后續操作
6.訪問頁面
此時通過瀏覽器訪問 localhost:8080 就可以打開一個新的 vue 頁面
嶄新的 vue 頁面
7.項目結構
截止目前的項目結構如圖
項目結構
由于是初學,為了先搞個東西出來,所以暫時先不管一些亂七八糟的配置,只挑跟這次相關的說(其實多了我也沒學到...)
8.查看 Vuex
既然是使用 Vuex 來實現筆記應用,我們就應該先查看一下構建的項目是否包含 Vuex 模塊。
node_modules 文件夾包含了現有的模塊,然而里面并沒有我們想要的 Vuex,不信自己去看
package.json 文件描述了項目包含的文件,項目如何運行等信息
package.json
9.安裝 Vuex
在命令行中輸入 npm install vuex --save:--save 就是將安裝信息寫入 package.json
已安裝了 Vuex
至此,所有前期工作已經準備完成,遺漏的部分將在實現過程中逐一解釋
搞起
零、思路
整個應用可拆分為三個組件
拆
一、index.html
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>vuex-note</title> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body></html>
這個沒什么說的,注意 div 的 ID 就行
二、main.js
import Vue from 'vue'import App from './App'import store from './store' Vue.config.productionTip = falsenew Vue({ el: '#app', store, components: { App }, template: '<App/>'})
1.在 import 時什么時候需要 ' ./ '?
從項目模塊中導出,引入時不需要 ./,而從自己寫的組件中引入時需要 ./
2.什么時候需要 import {aaa} from abc 這種加大括號的引入?什么時候不需要?
當 abc 中被導出的部分是 export aaa 時
當 import 的是被 export default 導出的部分時不加 {},并且可以起個別名
3.項目結構中并沒有 store 文件,只有 store 文件夾,那 import store from './store' 是什么意思?
不知道,求指教
4. new Vue 中單獨的 store 是什么意思?
ES6 的一種簡寫方式,縮寫之前是 store:store,這句話的意思是為全局注入 Vuex,這樣在各個組件中都可以通過 this.$store 去調用狀態庫,如果不在全局注入,則需要在每個組件中單獨引入,多了會很麻煩
三、store 下的 index.js
import Vue from 'vue'import Vuex from 'vuex'import getters from './getters'import mutations from './mutations'import actions from './actions'Vue.use(Vuex) const defaultNote = { id: +new Date(), title: '新建筆記' + new Date().getMilliseconds(), // 加時間是為了做一下區分 content: '筆記內容', fav: false}// 可以理解為一個狀態的倉庫 const state = { notes: [defaultNote], // 以數組方式存放所有的筆記 activeNote: defaultNote, // 用來記錄當前筆記 show: 'all' // 用于切換 全部 / 已收藏 兩種不同列表的標識}export default new Vuex.Store({ state, getters, mutations, actions})
1. Vue.use(Vuex) 是什么意思?
使用 Vuex,今后用 Vue-router 時也得來這么一出,只是得寫在 route 文件夾下的 index.js 文件中
2. +new Date() 是什么意思?
獲取時間戳的另一種寫法,等同于 new Date().getTime()
3.state,getters,mutations,actions 之間的關系?
state:如上所言狀態倉庫
getters:state 的修飾,比如 state 中有 str:"abc" 這么個屬性,而在很多組件中需要進行 str + "def" 的操作,如果在每個組件都進行 str + "def" 的操作未免太麻煩,于是可以在 getters 中增加:
strAdd(){ return this.str + "abc"}
今后在組件中使用 strAdd 就可以了
四、tool.vue
<template> <div id="tool"> <button class="add" @click="add_note">新增</button> <button class="fav" @click="fav_note">收藏</button> <button class="del" @click="del_note">刪除</button> </div></template><script type="text/javascript"> import { mapState, mapGetter, mapActions } from 'vuex' export default { name: 'tool', methods:{ ...mapActions(['add_note','del_note','fav_note']) } }</script><style type="text/css" scoped> #tool { width: 200px; height: 600px; border: 2px solid #ccc; float: left; } button { width: 100%; height: calc(100% / 3); font-size: 60px; }</style>
1.mapState, mapGetter, mapActions 都是什么?
這里有個非常好的解釋 http://www.imooc.com/article/14741
此外,當 methods 和 Vuex 的 actions 中具有同名的屬性 A 時,可使用 mapActions(['A']) 這種方式簡寫
注意:1、中括號不能省略;2、中括號內是字符串;3、展開運算符...不能省略
也可以取個別名,寫法如下,注意 [] 變成了 {}:
...map({ 本組件的屬性 : Vuex 中 actions 中的屬性})
需要傳入參數時,前提是 actions 中的屬性(方法)能接收參數:
methods:{ ...mapActions(['abc']) // 自定義一個方法,通過觸發這個方法調用之前重名的方法并傳入參數 tragger_abc(參數){ this.abc(參數) }}
2.scoped
對當前組件生效的 CSS
3.calc
使用時記得在運算符前后各加一個空格
五、list.vue
<template> <div id="list"> <div class="switch"> <button class="all" @click='get_switch_note("all")'>全部</button><button class="fav" @click='get_switch_note("fav")'>已收藏</button> </div> <div class="search"> <input type="text" placeholder="在這里搜索" v-model="search" /> </div> <div class="noteList"> <div class="note" v-for="note in search_filteredNote" :class="{favColor:note.fav===true,active:note.id===activeNote.id}" @click='get_select_note(note)'> <div class="title"> <p>{{note.title}}</p> </div> <div class="content"> <p>{{note.content}}</p> </div> </div> </div> </div></template><script type="text/javascript"> import { mapState, mapGetters, mapActions } from 'vuex' export default { name: 'list', data: function() { return { search: "" } }, computed: { ...mapState(['notes', 'activeNote']), ...mapGetters(['filteredNote']), // 二次過濾:在當前列表(全部 或 已收藏)中進行篩選,返回值被用在組件的 v-for 中 search_filteredNote() { if(this.search.length > 0) { // 如果輸入框有值,返回二次過濾的結果并加載 return this.filteredNote.filter(note => { if(note.title.indexOf(this.search) > 0) { return note } }) } else { // 輸入框沒值,不過濾,直接拿來加載 return this.filteredNote } } }, methods: { ...mapActions(['select_note', 'switch_note']), get_select_note(note) { this.select_note(note) }, get_switch_note(type) { this.switch_note(type) } } }</script><style type="text/css" scoped="scoped"> #list { width: 300px; height: 600px; border: 2px solid #ccc; float: left; margin-left: 10px; display: flex; flex-direction: column; } p { margin: 0; } .switch {} .switch button { height: 60px; width: 50%; font-size: 40px; } .search { border: 1px solid #CCCCCC } input { width: 100%; box-sizing: border-box; height: 50px; line-height: 50px; padding: 10px; outline: none; font-size: 20px; border: none; } .noteList { flex-grow: 1; overflow: auto; } .note { border: 1px solid #CCCCCC; } .favColor { background: pink; } .active { background: lightblue }</style>
1.data 中的 search 是干嘛的?可不可以寫在 computed 中?
用來與搜索框進行關聯。可以寫在 computed 中,但 computed 中的屬性默認都是 getter ,就是只能獲取值,如果想修改,需要設置 setter ,詳見官方文檔
六、edit.vue
<template> <div id="edit"> <div class="title"> <input type="text" placeholder="在這里輸入標題" v-model="activeNote.title"/> </div> <div class="content"> <textarea name="" placeholder="在這里吐槽" v-model="activeNote.content"></textarea> </div> </div></template><script type="text/javascript"> import { mapState, mapGetter, mapActions } from 'vuex' export default { name: 'edit', computed:{ ...mapState(['activeNote']) // 當本組件中 computed 中的屬性名與 Vuex 中的 state 屬性名相同時,就可以在 mapState() 中簡寫 } }</script><style type="text/css" scoped="scoped"> #edit { width: 300px; height: 600px; border: 2px solid #ccc; float: left; margin-left: 10px; display: flex; flex-direction: column; } .title { border: 1px solid #CCCCCC; } input { width: 100%; box-sizing: border-box; height: 50px; line-height: 50px; padding: 10px; outline: none; font-size: 20px; border: none; } .content { flex-grow: 1; background: orange; display: flex; flex-direction: column; } textarea { width: 100%; box-sizing: border-box; flex-grow: 1; resize: none; padding: 10px; font-size: 20px; outline: none; font-family: inherit; }</style>
七、actions.js
export default { add_note({commit}) { commit('ADD_NOTE') }, select_note({commit}, note) { commit("SELECT_NOTE", note) }, del_note({commit}) { commit("DEL_NOTE") }, fav_note({commit}) { commit("FAV_NOTE") }, switch_note({commit}, type) { commit("SWITCH_NOTE", type) }}
1.這是干什么?
這里的每個方法實際上是通過 commit 調用 mutations.js 中的方法;
舉個栗子:tool.vue 的 新增 按鈕上綁了一個 add_note 自定義方法,在 actions.js 中也定義一個同名的方法,這樣就可以在 tool.vue 中的 mapActions 中簡寫,就是下面這句:
# tool.vue...mapActions(['add_note','del_note','fav_note'])
而 actions.js 中的 add_note 去調用 mutations.js 中寫好的 ADD_NOTE 方法,而實際的添加操作也是在 ADD_NOTE 中,組件也好,actions 也好,最終只是調用 ADD_NOTE 。之所以這么做是因為 mutations 中的方法都是同步的,而 actions 中的方法是異步的,不過在本例里沒啥區別
八、getters.js
export default { filteredNote: (state) => { if(state.show === 'all') { return state.notes } else { return state.notes.filter((note) => { if(note.fav === true) { return note } }) } }}
實現一個過濾,根據 show 來判斷展示 全部筆記 還是 已收藏筆記
九、mutations.js
import { SWITCH_NOTE, ADD_NOTE, SELECT_NOTE, DEL_NOTE, FAV_NOTE } from './mutation-types'export default { [ADD_NOTE](state, note = { id: +new Date(), title: '新建筆記' + new Date().getMilliseconds(), content: '筆記內容', fav: false }) { state.notes.push(note) state.activeNote = note }, [SELECT_NOTE](state, note) { state.activeNote = note }, [DEL_NOTE](state) { for(let i = 0; i < state.notes.length; i++) { if(state.notes[i].id === state.activeNote.id) { state.notes.splice(i, 1) state.activeNote = state.notes[i] || state.notes[i - 1] || {} return } } }, [FAV_NOTE](state) { state.activeNote.fav = !state.activeNote.fav }, [SWITCH_NOTE](state, type) { state.show = type }}
1.export default 那里看著好熟悉
ES6 函數的一種寫法,中括號 + 常量 作為函數名,這里常量從其它文件引入
十、mutation-types.js
export const ADD_NOTE = "ADD_NOTE"export const SELECT_NOTE = "SELECT_NOTE"export const DEL_NOTE = "DEL_NOTE"export const FAV_NOTE = "FAV_NOTE"export const SWITCH_NOTE = "SWITCH_NOTE"
拋出常量,mutations.js 中的函數常量就是這里拋出的,查資料說是這么做便于一目了然都有那些方法。
當然,根據個人習慣,你也可以不這么寫
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答