中
秋
快
乐
前言
大家好 我是歌谣 今天给大家带来vuex的讲解
安装vite
yarn create vite -D
安装成功之后
yarn add vuex
依赖
代码语言:javascript复制{
"name": "vite-vue-project",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --port 3002",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.3.4",
"vuex": "^4.1.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.2.3",
"vite": "^4.4.5"
}
}
store中的index.js
代码语言:javascript复制import {createStore} from 'vuex'
const defaultValue={
count:1,
todos:[{
id:1,
text:"geyao",
done:false
}]
}
代码语言:javascript复制export default createStore({
state(){
return defaultValue
},
mutations:{
increment(state,payload={amount:1}){
return (state.count=state.count payload.amount)
}
},
actions:{
increment({commit},payload){
commit('increment',payload)
}
},
getters:{
double:(state)=>state.count*2,
getTodoById:state=>id=>state.todos.find((todo)=>todo.id===id)
}
})
Helloword.js
代码语言:javascript复制<script setup>
import { useStore } from "vuex"
import { computed } from "vue";
const store=useStore()
const {state}=store
const countDouble=computed(()=>
store.getters.double
)
</script>
<template>
<div class="card">
<p>{{ countDouble }}</p>
<button type="button" @click="store.commit('increment')">count is {{ state.count }}</button>
<button type="button" @click="store.dispatch('increment',{amount:20})">actions is {{ state.count }}</button>
<button type="button" @click="store.commit('increment')">count is {{ countDouble }}</button>
<p>
Edit
<code>componnets/helloworld</code>
</p>
</div>
</template>
<style scoped></style>
运行结果