這篇文章主要為大家展示了“怎么使用Vuex實現(xiàn)一個筆記應用”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“怎么使用Vuex實現(xiàn)一個筆記應用”這篇文章吧。
成都創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設計、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設與策劃設計,舒蘭網(wǎng)站建設哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設10多年,網(wǎng)設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:舒蘭等地區(qū)。舒蘭做網(wǎng)站價格咨詢:18982081108
預期目標
筆記具備如下基本功能
1.新增
2.刪除
3.收藏
4.在全部筆記和收藏筆記間切換
5.在當前列表中進行搜索

賣家秀

買家秀
準備工作
1.新建項目
選個文件夾存放項目,這里我用的是 Git Bush 執(zhí)行語句($ 符號是 Git Bush 中自帶的),你也可以使用命令行,一樣的

選擇項目存放位置
2.查看模塊(愛看不看)
查看一下全局安裝的模塊 npm list --depth=0 -global

查看全局安裝的模塊
3.創(chuàng)建項目
在命令行輸入 vue init webpack vuex-note 并做好設置,創(chuàng)建一個項目

這都什么鬼
4.簡單解釋一下各個配置都是干嘛的
vue init webpack vuex-note:初始化(init)一個使用 webpack 構建工具構建的 vue 項目,項目名為 vuex-note
Project name:項目名
Project description:項目描述
Author:朕
Vue build:構建方式,分為獨立構建和運行時構建,具體說明見如下鏈接,這里選擇獨立構建 standalone https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
Install vue-router:是否需要安裝 vue-router ,跳轉頁面用的,這里用不著,我過會學
Use ESLint to lint your code:ESLint 規(guī)范與法用的,可能你熟悉的寫法都是不標準的,如果采用 ESLint 則可能報錯,這里選擇 n
剩下的都是測試用的,一路 n
Should we run 'npm install' for you after the project has been created:是否需要直接替你安裝(npm install)相關的依賴,回車就行,之后會替你安裝各種玩意
5.安裝完后會有提示,我們接著按照提示走
先是 cd vuex-note 進入剛剛創(chuàng)建的 vue 項目文件夾

安裝完成
再通過 npm run dev 跑起項目

后續(xù)操作
6.訪問頁面
此時通過瀏覽器訪問 localhost:8080 就可以打開一個新的 vue 頁面

嶄新的 vue 頁面
7.項目結構
截止目前的項目結構如圖

項目結構
由于是初學,為了先搞個東西出來,所以暫時先不管一些亂七八糟的配置,只挑跟這次相關的說(其實多了我也沒學到...)
8.查看 Vuex
既然是使用 Vuex 來實現(xiàn)筆記應用,我們就應該先查看一下構建的項目是否包含 Vuex 模塊。
node_modules 文件夾包含了現(xiàn)有的模塊,然而里面并沒有我們想要的 Vuex,不信自己去看
package.json 文件描述了項目包含的文件,項目如何運行等信息

package.json
9.安裝 Vuex
在命令行中輸入 npm install vuex --save:--save 就是將安裝信息寫入 package.json

已安裝了 Vuex
至此,所有前期工作已經(jīng)準備完成,遺漏的部分將在實現(xiàn)過程中逐一解釋
搞起
零、思路
整個應用可拆分為三個組件

拆
每條筆記包括 編號(ID),標題(title),內(nèi)容(content),是否已收藏(fav) 四種信息
Vuex 中的 state 得有個地方存放 所有的筆記(notes)
而 收藏,刪除 操作只能對 當前的筆記 進行操作,因此我還需要一個標識用來記錄 當前的筆記(activeNote) 是哪個
包含 全部 和 收藏 兩種切換方式,因此還需要有一個標識來進行區(qū)分,就叫 show 吧,all 代表 全部,fav 就代表 已收藏
組件 ==> actions.js ==> mutations.js = > state:通過組件調用 actions 中的方法(dispatch),通過 actions 中的方法調用 mutations 中的方法(commit),通過 mutations 中的方法去操作 state 中的筆記列表(notes),當前筆記(activeNote)等等
一、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 = false
new 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 去調用狀態(tài)庫,如果不在全局注入,則需要在每個組件中單獨引入,多了會很麻煩
三、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(), // 加時間是為了做一下區(qū)分
content: '筆記內(nèi)容',
fav: false
}
// 可以理解為一個狀態(tài)的倉庫
const state = {
notes: [defaultNote], // 以數(shù)組方式存放所有的筆記
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:如上所言狀態(tài)倉庫
getters:state 的修飾,比如 state 中有 str:"abc" 這么個屬性,而在很多組件中需要進行 str + "def" 的操作,如果在每個組件都進行 str + "def" 的操作未免太麻煩,于是可以在 getters 中增加:
strAdd(){
return this.str + "abc"
}今后在組件中使用 strAdd 就可以了
mutations:簡單講就是用來修改 state 的,同步方法.常規(guī)調用 this.$store.commit
actions:簡單講用來調用 mutations 的,異步方法.常規(guī)調用 this.$store.dispatch
四、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、中括號內(nèi)是字符串;3、展開運算符...不能省略
也可以取個別名,寫法如下,注意 [] 變成了 {}:
...map({
本組件的屬性 : Vuex 中 actions 中的屬性
})需要傳入?yún)?shù)時,前提是 actions 中的屬性(方法)能接收參數(shù):
methods:{
...mapActions(['abc'])
// 自定義一個方法,通過觸發(fā)這個方法調用之前重名的方法并傳入?yún)?shù)
tragger_abc(參數(shù)){
this.abc(參數(shù))
}
}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 中?
用來與搜索框進行關聯(lián)。可以寫在 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 中的方法是異步的,不過在本例里沒啥區(qū)別
八、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
}
})
}
}
}實現(xiàn)一個過濾,根據(jù) 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: '筆記內(nèi)容',
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 函數(shù)的一種寫法,中括號 + 常量 作為函數(shù)名,這里常量從其它文件引入
十、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 中的函數(shù)常量就是這里拋出的,查資料說是這么做便于一目了然都有那些方法。
以上是“怎么使用Vuex實現(xiàn)一個筆記應用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)站標題:怎么使用Vuex實現(xiàn)一個筆記應用
本文地址:http://chinadenli.net/article0/ipcjio.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、做網(wǎng)站、網(wǎng)站收錄、網(wǎng)站維護、云服務器、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)