vuex
vuex做数据管理
- 先安装vuex
npm i vuex
- 在src下新建store下建立index.js文件用来管理个页面的数据
- src/store/index.js
//数据分块 import Vue from 'vue' import Vuex from 'vuex' import count from '../views/vuex/store' Vue.use( Vuex ); const store = new Vuex.Store({ modules:{ //数据分块的各个部分 count } }) export default store ```
- 在main.js中全局注册store
- src/main.js
import Vue from 'vue' import App from './App.vue' import store from './store' //这边 import axios from 'axios' Vue.prototype.$axios = axios //将axios挂载到原型中去 Vue.config.productionTip = false new Vue({ store,//这边 render: h => h(App), }).$mount('#app') ```
- 在每个页面文件下创建一个store.js文件用来管理当前页面的所有数据
- src/views/vuex/store.js
const COUNT = 'COUNT' export default { state:{ //储存状态(数据) count: 0 }, actions:{ //创建动作(创建方法)并发送动作(方法) count({ commit },index){ commit({ type:COUNT, payload:index }) } }, mutations:{ // 执行actions创建的方法 COUNT(state,actions){ state.count++ , actions.payload//获取传入的index } } }
- 在页面使用
this.$store
获取vuex数据this.$store.dispatch('actions的方法名',index)
获取vuex方法- index是需要传入的参数
- 写法
methods: { btnClick(index) { this.$store.dispatch('btnClick',index)//获取到store.js actions的方法并执行 }, computed: { //作用是将vuex中的stste中的数据给到page中,在script中可以直接用this.page;在页面中可以直接访问page page() { return this.$store.state.paging.page; }, }
vuex
const BTNCLICK = 'BTNCLICK'//定义常量,目的是唯一标识,为了让mutations获取actions中创建的方法
export default {
state: {
//在这里创建数据
},
actions:{
btnClick({commit},index) {//index是可选参数,可以不传
commit({
type:BTNCLICK ,
payload:index
})
}
},
mutations:{
BTNCLICK(state,actions){//是否要用到上面的state中的数据和actions中的参数,如果不用就不用写
if (actions.payload != state.page.pageNO) {
state.page.pageNO = actions.payload;
console.log("index", actions.payload);
}
}
}
}
三个参数(在vuex中):
state:存储数据的类与.vue文件中的data中的数据
actions:创建方法名
mutations:执行创建方法中的函数
在页面中使用:
- dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch(‘action方法名’,传入值(类似key,index,e))
- commit:同步操作,写法:this.$store.commit(‘mutations方法名’,值)
- 在computed:{}中用page() {return this.KaTeX parse error: Expected 'EOF', got '}' at position 26: …e.paging.page; }̲,可以将his.store.state.的数据给到page中,在js代码中直接用this.page去取数据,在html中直接用page去取数据{{page}}