如果你之前使用過vue.js,你一定知道在vue中各個組件之間傳值的痛苦,在vue中我們可以使用vuex來保存我們需要管理的狀態值,值一旦被修改,所有引用該值的地方就會自動更新,那么接下來我們就來學習一下vuex是如何修改狀態值的。
1. 搭建Demo
使用vue create 項目名創建一個項目,在src根目錄下創建一個components目錄並在該目錄下面創建2個組件:header.vue,content.vue,在App.vue根組件中進行引入然后展示,刪除不必要的組件。
<template>
<div style="height:60px;" class="header">
<span></span>
<span></span>
</div>
</template>
<script>
export default {
}
</script>
<style>
.header span{
display: inline-block;
width: 32px;
height: 32px;
cursor: pointer;
}
.header span:first-child{
background: red;
}
.header span:last-child {
background: blue;
}
</style>
<template> <div class="content" :style="`background: pink`"> Content </div> </template> <script> export default { mounted(){ } } </script> <style> .content { height: 600px; text-align: center; line-height: 600px; } </style>
<template>
<div id="app">
<Header></Header>
<Content></Content>
</div>
</template>
<script>
import Header from "./components/header";
import Content from "./components/content";
export default {
// 注冊組件
components: {
Header,
Content
}
};
</script>
<style>
</style>
頁面效果:

下面需要實現點擊紅色按鈕使得背景變為紅色,點擊藍色按鈕使得背景變成藍色,下面使用vuex實現。
2. 設置和獲取倉庫中的數據
先安裝vuex。
yarn add vuex
在src根目錄下創建store,然后創建一個index.js文件。
import Vuex from "vuex"; import Vue from "vue"; // 注冊插件 Vue.use(Vuex); // 創建倉庫實例 const store = new Vuex.Store({ // 倉庫的數據 state: { test_data: "this is some test data", color: "light-green" }, // 同步修改state的值 mutations: { // mutations下的方法第一個參數是固定state // 第二個參數是傳進來的參數 setColor(state, color) { state.color = color; } } }); export default store;
實現后的代碼
<template>
<div style="height:60px;" class="header">
<span @click="handleClick('red')"></span>
<span @click="handleClick('blue')"></span>
</div>
</template>
<script>
export default {
methods: {
handleClick(color){
// 不推薦使用這個方法來修改state的值
// this.$store.state.color = color;
// this.$store.commit調用mutations下面的方法
// 第一個參數就是mutations下面的的具體方法
// 第二個參數就是傳遞給方法的參數
this.$store.commit("setColor", color)
}
}
}
</script>
<style>
.header span{
display: inline-block;
width: 32px;
height: 32px;
cursor: pointer;
}
.header span:first-child{
background: red;
}
.header span:last-child {
background: blue;
}
</style>
<template>
<div class="content" :style="`background: ${$store.state.color}`">Content</div>
</template>
<script>
export default {
mounted() {
// this.$store當把倉庫引入到main.js的時候,組件可以通過this.$stroe獲取倉庫的數據
console.log(this.$store);
}
};
</script>
<style>
.content {
height: 600px;
text-align: center;
line-height: 600px;
}
</style>
import Vue from 'vue' import App from './App.vue' import store from './store' Vue.config.productionTip = false new Vue({ render: h => h(App), store, }).$mount('#app')
