Vuex實現(xiàn)數(shù)據增加和刪除功能
首先,我們要安裝vuex,執(zhí)行命令yarn add vuex
1.編寫state數(shù)據
//vuex/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = {
bookList: [
{id: 1, name: '西游記'},{id: 2, name: '水滸傳'},
{id: 3, name: '紅樓夢'},{id: 4, name: '三國演義'}
]
}
export default new Vuex.Store({
state
})
2.組件調用state數(shù)據進行展示
我們的目的是把state數(shù)據賦值給vue組件進行使用,其實,這里有兩種常用方法
//Home.vue
<p v-for='item in bookList'>{ {item.name} }<p/>
//方法一:通過computed的計算屬性直接賦值,computed屬性可以在輸出前,對data中的值進行改變,我們就利用這種特性把state值賦值給vue模板中的data進行使用
computed: {
bookList( ) {
return this.$store.state.bookList;
}
}
//方法二:通過mapState的對象來賦值
import { mapState } from 'vuex';//首先在組件內引入mapState
computed: {
...mapState(['bookList'])
}
方式二是我們經常用到的簡寫方式
基本的數(shù)據獲取,就是這樣的實現(xiàn),此時我們看頁面,就會循環(huán)展示state中的bookList數(shù)據
3.利用mutation、action實現(xiàn)增加刪除數(shù)據
//vuex/index.js
const mutations = {
ADD_ITEM(state,item) {
state.bookList.push(item)
}
}
const mutations = {
ADD_ITEM(state,item) {
state.bookList.push(item)
},
DEL_ITEM(state,id) {
state.bookList.map((v,i)=> {
if(v.id == id){
state.bookList.splice(i,1)
}
})
}
}
const actions = {
add_item({commit},item) {
commit('ADD_ITEM',item)
},
del_item({commit},id) {
commit('DEL_ITEM',id)
}
}
export default new Vuex.Store({
state,mutations,actions
})
//Home.vue
<button @click='add_item'>ADD</button>
<p v-for='item in bookList' @click='delItem(item.id)'>{ {item.name} }<p/>
import { mapState, } from 'vuex';
computed: {
...mapState(['bookList'])
}
methods: {
add_item() {
let newObject = {id:this.bookList.length,name:'葫蘆娃'}
this.$store.dispatch('add_item',newObject)
},
delItem(id) {
this.$store.dispatch('del_item',id)
}
}
利用action派發(fā)mutation事件,實現(xiàn)增加和刪除的操作
這里有一個很重要的概念: mutation是唯一修改state的方法,而action是操作mutation觸發(fā)commit修改state的方式
4.使用getters過濾state數(shù)據
//vuex/index.js
const getters = {
newBookList:function( state ){
return JSON.parse(JSON.stringify(state.bookList)).splice(0,1)
}
}
這樣,我們在組件內部這樣輸出
mounted( ) {
console.log(this.$store.getters.newBookList)
console.log(this.bookList)
}
我們通過JSON拷貝,既可以得到過濾之后的state數(shù)據(1條數(shù)據),也可以得到原state數(shù)據(4條數(shù)據),個人理解,getters的作用就在這里
以上這篇Vuex實現(xiàn)數(shù)據增加和刪除功能就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue淺析axios二次封裝與節(jié)流及防抖的實現(xiàn)
axios是基于promise的HTTP庫,可以使用在瀏覽器和node.js中,它不是vue的第三方插件,vue-axios是axios集成到Vue.js的小包裝器,可以像插件一樣安裝使用:Vue.use(VueAxios,?axios),本文給大家介紹axios的二次封裝和節(jié)流與防抖2022-08-08
在Vue項目中用fullcalendar制作日程表的示例代碼
這篇文章主要介紹了在Vue項目中用fullcalendar制作日程表,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08
vue基礎之data存儲數(shù)據及v-for循環(huán)用法示例
這篇文章主要介紹了vue基礎之data存儲數(shù)據及v-for循環(huán)用法,結合實例形式分析了vue.js使用data存儲數(shù)據、讀取數(shù)據及v-for遍歷數(shù)據相關操作技巧,需要的朋友可以參考下2019-03-03

