_src_求和案例_多元件共享資料
阿新 • • 發佈:2022-06-05
<template> <div> <h1>當前求和為:{{sum}}</h1> <h3>當前求和放大10倍為:{{bigSum}}</h3> <h3>我在{{school}},學習{{subject}}</h3> <h3 style="color:red">Person元件的總人數是:{{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(n)">當前求和為奇數再加</button> <button @click="incrementWait(n)">等一等再加</button> </div> </template> <script> import {mapState,mapGetters,mapMutations,mapActions} from 'vuex' export default { name:'Count', data() { return { n:1, //使用者選擇的數字 } }, computed:{ //藉助mapState生成計算屬性,從state中讀取資料。(陣列寫法) ...mapState(['sum','school','subject','personList']), //藉助mapGetters生成計算屬性,從getters中讀取資料。(陣列寫法) ...mapGetters(['bigSum']) }, methods: { //藉助mapMutations生成對應的方法,方法中會呼叫commit去聯絡mutations(物件寫法) ...mapMutations({increment:'JIA',decrement:'JIAN'}), //藉助mapActions生成對應的方法,方法中會呼叫dispatch去聯絡actions(物件寫法) ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'}) }, mounted() { // const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'}) // console.log(x) }, } </script> <style lang="css"> button{ margin-left: 5px; } </style>
<template> <div> <h1>人員列表</h1> <h3 style="color:red">Count元件求和為:{{sum}}</h3> <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 }, sum(){ return this.$store.state.sum } }, methods: { add(){ const personObj = {id:nanoid(),name:this.name} this.$store.commit('ADD_PERSON',personObj) this.name = '' } }, } </script>
//該檔案用於建立Vuex中最為核心的store import Vue from 'vue' //引入Vuex import Vuex from 'vuex' //應用Vuex外掛 Vue.use(Vuex) //準備actions——用於響應元件中的動作 const actions = { /* jia(context,value){ console.log('actions中的jia被呼叫了') context.commit('JIA',value) }, jian(context,value){ console.log('actions中的jian被呼叫了') context.commit('JIAN',value) }, */ jiaOdd(context,value){ console.log('actions中的jiaOdd被呼叫了') if(context.state.sum % 2){ context.commit('JIA',value) } }, jiaWait(context,value){ console.log('actions中的jiaWait被呼叫了') setTimeout(()=>{ context.commit('JIA',value) },500) } } //準備mutations——用於操作資料(state) const mutations = { JIA(state,value){ console.log('mutations中的JIA被呼叫了') state.sum += value }, JIAN(state,value){ console.log('mutations中的JIAN被呼叫了') state.sum -= value }, ADD_PERSON(state,value){ console.log('mutations中的ADD_PERSON被呼叫了') state.personList.unshift(value) } } //準備state——用於儲存資料 const state = { sum:0, //當前的和 school:'尚矽谷', subject:'前端', personList:[ {id:'001',name:'張三'} ] } //準備getters——用於將state中的資料進行加工 const getters = { bigSum(state){ return state.sum*10 } } //建立並暴露store export default new Vuex.Store({ actions, mutations, state, getters })