若是你以前使用過vue.js,你必定知道在vue中各個組件之間傳值的痛苦,在vue中咱們能夠使用vuex來保存咱們須要管理的狀態值,值一旦被修改,全部引用該值的地方就會自動更新,那麼接下來咱們就來學習一下vuex是如何修改狀態值的。vue
使用vue create 項目名建立一個項目,在src根目錄下建立一個components目錄並在該目錄下面建立2個組件:header.vue,content.vue,在App.vue根組件中進行引入而後展現,刪除沒必要要的組件。vuex
<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>
頁面效果:app
下面須要實現點擊紅色按鈕使得背景變爲紅色,點擊藍色按鈕使得背景變成藍色,下面使用vuex實現。ide
先安裝vuex。學習
yarn add vuex
在src根目錄下建立store,而後建立一個index.js文件。this
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;
實現後的代碼spa
<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')