0、vuex是什么:全局的状态存储仓库
1、为何要用:主要可以解决兄弟、或无关联组件之间、全局的数据存储传递的问题
2、使用方法:
state属性 可以看做全局的data
getters属性 可以看做全局的computed属性
mutations 可以看做全局的methods方法
actions 可以看做全局的异步调用methods方法
modules 一整个模块 略
3、代码引入:main.js
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: { // 把state看出全局的data
name: 'xl'
},
getters: { // 全局的computed属性
fullName: state =>{
return '我的名字叫'+state.name
}
},
mutations: { //全局的methods方法 回调函数使用必须用this.$store.commit()
changeNameFun(state, payload) {
state.name = payload
}
},
actions: { //提交mutations 允许异步操作
changeNameFunAsync(context, payload) {
setTimeout( ()=>{
context.commit('changeNameFun', payload)
}, 2000);
}
}
})
new Vue({
el: '#app',
store, // 将store挂载到vue实例当中
render: h=> h(App)
})
3.1、代码引入 另一种写法 将store分离出来新建一个store.js页 然后向外导出整个vuex对象
main.js文件引入
import store from './store'; //在同级新建store.js文件 引入store对象
new Vue({
router,
store, // 将store挂载到vue实例当中
render: h => h(App)
}).$mount('#app')
新建的文件store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { // 把state看出全局的data
name: 'xl'
},
getters: { // 全局的computed属性
fullName: state =>{
return '我的名字叫'+state.name
}
},
mutations: { //全局的methods方法 回调函数使用必须用this.$store.commit()
changeNameFun(state, payload) {
state.name = payload
}
},
actions: { //提交mutations 允许异步操作
changeNameFunAsync(context, payload) {
setTimeout( ()=>{
context.commit('changeNameFun', payload); //在actions里调mutations属性的函数,第一个参数是方法名,第二个是数据
}, 2000);
}
}
})
4、在page.vue中的使用
this.$store.state.name //定义的变量name
this.$store.getters.fullName //定义的getters fullName
changeNameFun() { this.$store.commit('changeNameFun', 'xl小姐姐') } // 通过commit方法,传进去第一个参是方法名,第二个参是数据
changeNameFunAsync() { this.$store.dispatch('changeNameFunAsync', 'xl小姐姐爱coding')} //通过dispatch方法,传进去第一个参是方法名,第二个参是数据
5、modules 略