天天看點

如何在項目中使用Vuex

在老項目中

在老項目中 使用vuex 需要下載下傳vuex包

步驟:

1.下載下傳安裝包 npm i vuex

2.在src檔案中建立一個檔案 store(不是固定檔案名 而是約定名字)

3.建立一個index.js 檔案 放置具體代碼

import Vue from 'vue'
		import Vuex from 'vuex'

		Vue.use(Vuex)

		const store = new Vuex.Store({
		  state: {
		    count: 0
		  }
		})
		export defalut storeimport Vue from 'vue'
		import Vuex from 'vuex'

		Vue.use(Vuex)

		const store = new Vuex.Store({
		  state: {
		    count: 0
		  }
		})
		export defalut store
           

4.在src/main.js中導入store注入Vue執行個體

import store from ‘./store’  //省略其他
		new Vue({
		    store   //注入Vue執行個體
		})
           

5.在元件中使用store

this.$store.state   //擷取公共資料
           

在新項目中

如何在項目中使用Vuex