vuex是状态管理器,简单的讲就是管理前端数据的。他是一个单例的对象(也就是共享的数据)
做用:传值,储存
使用场景:用户的登陆信息,某个全局须要的属性或状态,购物车
例子及步骤:
场景一:
1.安装vuex npm install vuex --save
2.安装好以后在src文件在建立一个store文件夹,在此文件夹中建立一个store.js文件。
3.store.js文件中 首先引入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
而后将vuex运用到vue中 Vue.use(Vuex)
而后声明一个 state(存放所有的状态)
const state={
count:0,
}
最后将state暴露出来
export default new Vuex.Store({
state,
})
4.在main.js中引入store.js文件
import store from './store/store';
引入只有store须要和vue的实例关联起来
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
5.在用的页面直接使用
<p>{{$store.state.count}}</p>
此时页面上显示的应该是0
6.若须要改变全局存储的count此时咱们须要用到mutations
7.在store.js中继续写
声明一个 mutations(用来改变state中的全局变量)
const mutations={
<!--方法-->
add(state){
state.count++
},
delete(state){
state.count--
},
}
8.一样暴露mutations
export default new Vuex.Store({
mutations,
})
9.在用的页面进行使用
<p>{{$store.state.count}}</p>
<button @click="addF">+</button>
<button @click="delF">-</button>
computed:{
count:function (state) {
return store.state.count
},
},
methods:{
addF(){
// 调运添加的方法
<!--提交的时候要用commit进行提交给mutations-->
this.$store.commit('add')
},
delF(){
// 调运添加的方法
<!--提交的时候要用commit进行提交给mutations-->
this.$store.commit('delete')
},
}
这样就能够了
场景二:
咱们在作国际化的时候,会全局存储此时是中文状态仍是英文状态,那么此时咱们能够用到vuex
在store.js中继续写
const state={
lang:false
}
const mutations={
E(state){
state.lang=true
},
C(state){
state.lang=false
}
}
在使用的页面
<p>{{$store.state.lang==false ? '关' : '开'}}</p>
<button @click="addF1">开</button>
<button @click="delF1">关</button>
methods:{
addF1(){
// 调运添加的方法
this.$store.commit('E')
},
delF1(){
// 调运添加的方法
this.$store.commit('C')
},
}
此时在全局能够看到是英文状态仍是中文状态。
复制代码