1、Vuex有啥用(非官方解释)
举例,组件a b 使用了同一个数据源count,当操作a的时候count++,同时让b中的count数据也同时更新,就可以使用vuex实现。
2、举个栗子
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state){
state.count++;
},
minus(state){
state.count--;
}
},
actions: {
}
})
现在拥有了一个数据count和两个方法add minus
view中调用
<template>
<div class="asd">
<p @click="fn1()">增加{{count}}</p>
<p @click="fn2()">减少{{count}}</p>
</div>
</template>
<script>
export default {
name: "asd",
computed:{
count(){
return this.$store.state.count
}
},methods:{
fn1(){
console.log(this.$store.state.count)
return this.$store.commit('add')
},
fn2(){
console.log(this.$store.state.count)
return this.$store.commit('minus')
}
},mounted(){
console.log(this.$store.state.count)
}
}
</script>
<style scoped>
</style>
通过计算属性绑定store中的count值,并显示在页面上
通过点击事件绑定store中的两个方法。
此时点击增加,和减少,count随操作变化。
官方示例:https://jsfiddle.net/n9jmu5v7/1269/
ok 现在在第一个页面通过点击增加文字修改了count后,换一个页面在调试台输出这个值,试试。
网友评论