1.安装:npm i vuex
2.新建文件夹store / store.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
state:{
/*state里面存储的都是公共的数据*/
source: 0, //存的值
},
mutations:{
// state 就是上面那个state val就是你传过来的参
setValue(state, val) {
state.source = val;
},
}
export default store
3.页面传值到vuex
methods:{
checkPro(source) {
this.$store.commit("setValue", source);
//setValue传值的方法名
// console.log('source',this.$store.state.source)
// this.source = this.$store.state.source
},
4.页面使用vuex的值
$store.state.source
补充1:main.js引入vuex
import store from '../store/store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
补充2:watch和computed的使用
```javascript
//在组件中取vuex的值的时候一定要使用计算属性,不然会存在接收不到的情况
computed: {
source() {
return this.$store.state.source
},
},
//调用的时候要是有watch,不然会存在调用不执行的情况
watch: {
source() {
this.checkPayPower()
},
},
在方法中使用source这个参数的时候就直接this.source就可以啦!!!!!