import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({ el:'#root', render: h => h(App), store, beforeCreate(){ Vue.prototype.$bus = new Vue(); } }) <template> <div > <Count/> <Person/> </div> </template>
<script>
import Count from './components/Count.vue' import Person from './components/Person.vue' export default{ name:'App', components:{ Count, Person }, data() { return { } }, } </script>
<style lang="css"> </style> //该文件用于创建Vuex中最为核心的store import Vue from 'vue' import Vuex from 'vuex'
Vue.use(Vuex) //准备actions——用于响应组件中的动作 const actions = { jia(context,value){ context.commit('JIA',value) }, jian(context,value){ console.log('方法被调用了') context.commit('JIAN',value) } } //准备mutations——用于操作数据(store) const mutations = { JIA(state,value){ state.sum += value }, JIAN(state,value){ state.sum -= value }, ADD_PERSONS(state,value){ state.personList.unshift(value) } } //准备state——用于存储数据 const state = { sum:0, //当前的和 school:'尚硅谷', subject:'数学', personList:[ {id:'001',name:'张三'} ] } //用于将state中的数据进行加工 const getters = { bigSum(state){ return state.sum*10 } }
export default new Vuex.Store({ actions, mutations, state, getters }) <template> <div> <h1>人员列表</h1> <input type="text" placeholder="请输入名字" v-model="name"> <button @click="add">添加</button> <ul> <li v-for="p in personList" :key="p.id">{{p.name}}</li> </ul> </div> </template>
<script> import {nanoid} from "nanoid"; export default{ name:'Person', data() { return { name:'' } }, computed:{ personList(){ return this.$store.state.personList } }, methods:{ add(){ const personObj = {id:nanoid(),name:this.name} this.$store.commit('ADD_PERSONS',personObj) this.name='' } } } </script>
<style>
</style> <template> <div> <h1>当前求和为:{{sum}}</h1> <h1>十倍的和为:{{bigSum}}</h1> <h1>{{xuexiao}}</h1> <h1>{{xueke}}</h1> <h3>下方总人数为:{{$store.state.personList.length}}</h3> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button @click="increment(n)">+</button> <button @click="decrement(n)">-</button> <button @click="incrementOdd">当前求和为基数再加</button> <button @click="incrementWait">等一等再加</button> </div> </template>
<script> import {mapState,mapGetters,mapMutations} from "vuex"; export default{ name:'Count', data() { return { n:1, //用户选择的数字 } }, methods:{
...mapMutations({increment:'JIA',decrement:'JIAN',personList:'personList'}),
incrementOdd(){ if(this.$store.state.sum % 2){ this.$store.dispatch('jia',this.n) } },
incrementWait(){ setTimeout(()=>{ this.$store.dispatch('jia',this.n) },500) } }, computed:{ //借助mapstate生成计算属性。从state中读取数据。(对象写法) // ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}) //数组写法 ...mapState(['sum','school','subject']),
...mapGetters({bigSum:'bigSum'}) }
} </script>
<style> button{ margin-left: 5px; } </style> 标签:vue,15,name,sum,value,mapstate,state,import,store From: https://www.cnblogs.com/hbro/p/18041269