文章目录
目录
在src中创建store文件夹,在文件夹中创建index.js
一、什么是vuex?
vuex是一个专门为vue.js应用程序开发得状态管理模式,vuex存放得状态是响应式的,更改状态只有唯一的途径显示的提交(commit)触发mutation更改state
二、使用步骤
1.在cmd上面安装vuex依赖
首先在项目文件夹下打开cmd命令
输入
npm install vuex@next --save
然后我们可以在package.json里面看到这样一行代码
"vuex": "^4.0.2"
2.配置vuex
vuex中有四个参数分别是
state 数据源(相当于data)
getters 计算属性
mutations 修改state的方法
actions 提交修改
在src中创建store文件夹,在文件夹中创建index.js
在index.js中写入以下内容
import {createStore} from 'vuex'
const store = createStore({
state:{
},
getters:{
},
mutations:{
},
actions:{
}
})
export default store;
在main.js中引入
import store from "./store";
createApp(App).use(store).mount('#app')
3. vuex使用方法
首先注意在页面里面写需要先进行引入对应的状态
state
在store文件里写
state:{
name:'张三'
},
在页面里写
<template>
<div class="hello">
{{name}}
</div>
</template>
<script>
import {useStore} from 'vuex'
import {ref} from 'vue'
export default {
setup(){
let name = ref('')
name.value = useStore().state.name
return{
name
}
}
}
</script>
getters
getters:{
num(state){
return state.name + '这是getters拼接的'
}
},
mutations
mutations:{
add(state,n){
// n是接收的参数
state.price += n
}
},
action
actions:{
addPrice(context,n){
// 第一个参数是上下文,第二个是接收的参数
context.commit('add',n)
}
}