Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
1、安装vuex
cnpm/npm install vuex --save
package.json中查看是否安装成功
2、在src下创建store文件夹,在创建一个js文件命名可以使默认的index.js 也可自己命名例如store.js,在stroe.js中引用并使用vuex
import Vue from vue
import Vuex from vuex
Vue.use(Vuex)
export const store = new Vuex.Store({
state: { //用来存储数据
},
getters: {//获得数据状态
},
mutations: { //用来更改数据状态
},
actions: { //应用mutations
}
})
3、在main.js中引用store.js文件或者index.js
import {index} from './store' //默认index.js
import {store} from './store/store.js' //store.js
4、实例化store
new Vue({
el: '#app',
store,
router,
components: { App },
template: '<App/>'
})
5、存储数据 存到store中
created: function() {
axios.get("/api/data.json").then(data => {
console.log(data.data);
this.$store.commit("setcommit", data.data); //用commit进行存储 setcommit是方法,后面的data.data是数据
});
}
6、在store.js进行数据保存
state: { //用来存储数据
commitsum: {}
},
mutations: { //用来更改数据状态
setcommit(state, data) {
state.commitsum = data
}
}
7、数据存储完毕可以调用
HTML:
<tbody v-for="(newpa,index) in newpazz" :key="index">
<tr>
<td row="3">{{newpa.name}}</td>
</tr>
</tbody>
JS:
computed: {
newpazz() {
return this.$store.state.commitsum;
}
}
在使用newpazz()中 有时候会报错 was assigned to but it has no setter.
解决:
computed: {
newpazz() {
get(){
return this.$store.state.commitsum;
},
set(){}
}
}
8、解决普通请求删除功能无法自动刷新 展示到页面上
(1)、将循环的数据存储到vuex中 store.js
created: function() {
axios.get("/api/data.json").then(data => {
let arrays = [];
for (let key in data.data) {
data.data[key].id = key;
arrays.push(data.data[key]);
}
this.$store.commit("setcommit", arrays);
// this.newda = arrays;
// console.log(this.newda);});
(2)、vuex中进行保存数据 store.js
state: { //用来存储数据
commitsum: {}
},
mutations: { //用来更改数据状态
setcommit(state, data) {
state.commitsum = data
},
}
(3)、vue组件中可以进行调用
<div class="col-md-4">
<table class="table">
<tr>
<th>品种</th>
<th>删除</th>
</tr>
<tr v-for="(item,index) in newpazz" :key="index">
<td>{{item.name}}</td>
<td v-on:click="removes(item)">删除</td>
</tr>
</table>
</div>
computed: {
newpazz: {
get() {
return this.$store.state.commitsum;
},
set() {}
}
},
(3)、根据删除的函数 将删除的内容调用传给vuex进行操作
methods: {
removes(item) {
axios.delete("/api/data/" + item.id + "/.json").then(data => {
this.$store.commit("remove", item);
});
}
(4)、store中进行删除实现更新
mutations: { //用来更改数据状态
setcommit(state, data) {
state.commitsum = data
},
remove(state, data) {
state.commitsum.forEach((item, index) => {
if (item == data) {
state.commitsum.splice(index, 1)
// console.log(3333)
}
});
}
}
用这种方法实现点击删除后,删除成功后,后台数据更改,前台数据也自动删除,这样就实现了删除功能的自动刷新
设置完属性可通过getters来获得属性状态
getMenuItems:state=>state.menuItems
如何调用?
在computed中可以使用
getMenuItems(){
//return this.$store.state.menuItems
return this.$store.getters.getMenuItems
}
}