1.先下载好,npm install vuex --save; 2.在src文件新建一个store文件,里面在建个index.js; 3.在index.js;
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { saveBookName: [] // 自己定义的变量名 }, mutations: { // 就相当于函数 去操作处理state里面的数据; addbook: (state) => { localStorage.setItem('bookarray', state.saveBookName) } } })我现在要把收藏的书籍,保存在一个数组里面;然后在书架页面,全部展示出来,用于增删查改; book.vue
bookShelf(bookId){ // 收藏按钮执行的事件 this.$refs.putBookshelf.setAttribute('disabled',true); this.$refs.putBookshelf.className = 'active'; this.$store.state.saveBookName.push(bookId); // 把id push到数组里面; this.$store.commit('addbook'); // 同时把他存在localStorage里面; }bookShelf.vue 书架页面
computed: { // 计算属性 saveBookName() { let localData = window.localStorage.getItem('bookarray').split(',') // 转化为数组; if(this.$store.state.saveBookName.length === 0){ // 存储的数据长度为0,就证明刷新了,就没有了, 就要从localStorage 取 return localData; }else{ return this.$store.state.saveBookName; //没有刷新,就直接取 } } }用了vuex,储存的data就相当于是全局变量;刷新一下,就又回到初始值了; 最后还是要依靠localStorage来,所以vuex的核心功能还有待挖掘;