vue3 Vuex

4 篇文章 0 订阅

1、store配置

	import {createStore} from 'vuex'
	
	const storeData={
	      state:() => ({}),
		  getters:{},
		  mutations:{},
		  actions:{},
		  modules:{}
	}
	const store=createStore(storeData)
	export default store
	
	import App from './App.vue'
	import store from "./store/index";
	
	const app=createApp(App)
	app.use(store)
	app.mount('#app')

2、State

(1)State定义:state保存数据

	state: () => ({
	    counter: 100,
	    name: "coderwhy",
	    level: 100,
	    avatarURL: "http://xxxxxx",
	    friends: [
	      { id: 111, name: "why", age: 20 },
	      { id: 112, name: "kobe", age: 30 },
	      { id: 113, name: "james", age: 25 }
	    ]
	 }),

(2)State使用:

<template>
  <div class="app">
    <h2>Home当前计数: {{ $store.state.counter }}</h2>
  </div>
</template>

<script setup>
  import { toRefs } from 'vue'
  import { useStore } from 'vuex'

  const store = useStore()
  const { counter } = toRefs(store.state)
  
  function increment() {
    // store.state.counter++
    store.commit("increment")
  }
</script>

3、Getter

(1)Getter定义:getter,转化和返回state中的数据

参数为state、getters,如需传入参数,则返回一个函数,参数的参数为getters的传入参数。

	 getters: {
	    // 1.基本使用
	    doubleCounter(state) {
	      return state.counter * 2
	    },
	    totalAge(state) {
	      return state.friends.reduce((preValue, item) => {
	        return preValue + item.age
	      }, 0)
	    },
	    // 2.在该getters属性中, 获取其他的getters
	    message(state, getters) {
	      return `name:${state.name}level:${state.level} friendTotalAge:${getters.totalAge}`
	    },
	    // 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
	    getFriendById(state) {
	      return function(id) {
	        const friend = state.friends.find(item => item.id === id)
	        return friend
	      }
	    }
	  },

(2)getter使用

	<template>
	  <div class="app">
	    <h2>doubleCounter: {{ $store.getters.doubleCounter }}</h2>
	    <h2>friendsTotalAge: {{ $store.getters.totalAge }}</h2>
	    <h2>message: {{ $store.getters.message }}</h2>
	
	    <!-- 根据id获取某一个朋友的信息 -->
	    <h2>id-111的朋友信息: {{ $store.getters.getFriendById(111) }}</h2>
	    <h2>id-112的朋友信息: {{ $store.getters.getFriendById(112) }}</h2>
	  </div>
	</template>
	
	<script setup>
	  import { computed, toRefs } from 'vue';
	  import { useStore } from 'vuex'
	  const store = useStore()
	  const { message } = toRefs(store.getters)
	  const message1 = computed(() => store.getters.message)
	  function changeAge() {
	    store.state.name = "kobe"
	  }
	</script>

4、Mutations

(1)Mutations定义:mutations修改state中的数据,

注意点:mutations执行同步代码,不要在mutations中执行异步操作,异步请求在actions中执行。
只能在mutations中修改state,在actions中不能直接修改state,必须触发mutations才能修改state。
Mutations参数是state和传入参数。

	import { CHANGE_INFO } from './mutation_types'
	mutations: {
	    increment(state) {
	      state.counter++
	    },
	    changeName(state, payload) {
	      state.name = payload
	    },
	    incrementLevel(state) {
	      state.level++
	},
	[CHANGE_INFO](state, newInfo) {
	      state.level = newInfo.level
	      state.name = newInfo.name
	    }
	}

(2)Mutations使用:mutations使用commit()提交

	<script setup>
	import { useStore } from 'vuex'
	
	const store = useStore()
	store.commit("changeName", "王小波")
	store.commit("incrementLevel")
	store.commit(CHANGE_INFO, {
	  name: "王二",
	  level: 200
	})
	</script>

5、Actions

(1)Actions定义:

如果网络请求的数据要保存在state中,网络请求可以在actions中操作。
Actions中不能直接修改state,要修改state只能通过调用mutations。
Actions的参数是context和传入参数,可以从context.commit()、context.state、context.getters。

 actions: {
    incrementAction(context) {
      context.commit("increment")
    },
    changeNameAction(context, payload) {
      context.commit("changeName", payload)
    },
    fetchHomeMultidataAction(context) {
      //返回一个promise,利用 resolve()返回参数,表示actions已经执行完毕
      return new Promise(async (resolve, reject) => {
        const res = await fetch("http://123.207.32.32:8000/home/multidata")
        const data = await res.json()
        // 修改state数据
        context.commit("changeBanners", data.data.banner.list)
        context.commit("changeRecommends", data.data.recommend.list)
        resolve("aaaaa")
      })
    }
  },

(2)Actions使用dispatch()派发:

	<script setup>
	import { useStore } from 'vuex'
	const store = useStore()
	function counterBtnClick () {
	  store.dispatch("incrementAction")
	}
	function nameBtnClick () {
	  store.dispatch("changeNameAction", "aaa")
	}
	//告诉Vuex发起网络请求,actions返回一个promise,表示actions已经执行完毕。
	store.dispatch("fetchHomeMultidataAction").then(res => {
	  console.log("home中的then被回调:", res)
	})
	
	</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值