天天看點

vue項目中引入vuex

vue項目中引入vuex

如果說vue-router 解決了vue 元件與路由的一一映射問題,那vuex就是對應解決了vue的狀态管理。

如果對vur-router引入和vue基礎項目搭建有疑惑的讀者可以移步

vue 項目中引入vue-router

由于vuex同樣是外部依賴,是以安裝也就是vuex的第一步:

npm install vuex --save
           

在src目錄下建立store檔案夾

vue項目中引入vuex
index.js
//引入外部依賴
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
//建立store執行個體
const store = new Vuex.Store({
  state: {
    name: 'Rowland'
  },
  mutations: {
    changeName(state) {
      state.name = 'lily';
    }
  }
})
//導出store
export default store;
           

main.js中添加store

import Vue from 'vue'
import App from './App.vue'


import store from './store';

new Vue({
  render: h => h(App),
  store
}).$mount('#app')
           

這樣就可以在元件中調用以及在mutation中聲明的方法了

$store.state.name
           
methods: {
    handleChildOneClick() {
      this.$store.commit('changeName');
    }
  }
           

繼續閱讀