[Vue] Build a vuex environment

1. Download and install vuex npm i vuex
2. Create src/store/index.js This file is used to create the most core  store in Vuex

import Vue from 'vue'
import Vuex from 'vuex'	// 引入Vuex

Vue.use(Vuex)	// 应用Vuex插件

// 准备actions——用于响应组件中的动作
const actions = {

}

// 准备mutations——用于操作数据(state)		
const mutations = {

}
	
// 准备state——用于存储数据
const state = {
}			

// 创建并暴露store
export default new Vuex.Store({
	actions,
	mutations,
	state,
})

3. Pass in the store configuration item when creating vm in src/main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store'	// 引入store

Vue.config.productionTip = false

new Vue({
	el: '#app',
	render: h => h(App),
	store,										// 配置项添加store
	beforeCreate() {
		Vue.prototype.$bus = this
	}
})

process:

  1. Install the plugin and reference it in main.js

Only after writing the previous configuration items, vue will recognize the configuration items of this store, and there will be

If vue finds that there are configuration items that it does not recognize, it will be discarded

It is found that there is a $store on both the component and the vm

  1. Create a store folder and create index.js in it

It is found that the error is reported because the location of the store is not created correctly

The store should be created after vue.user (vuex)

Cause Analysis

When we quote what we wrote in index.js in the store, when the tenth line is imported, the code in index.js in the store is executed

That is to say, the store has been created at this time

Then go back to main.js to create vue, that is, even the vue instance is not created, so how to put the store on the vm

But if you take it for granted, replace the reference and use position. The same error is reported

It was found that changing the position was exactly the same as the previous error

In fact, this is a problem of vue parsing import

Normal quotes here

output

change its order

Discovery or import priority call

That is to say, for vue cli, it will first scan the content of import and execute import sequentially

The solution is to write the vue.use(Vuex) here above the index.js folder of the store folder, before creating the store

store/index.js

src/main.js

Then we observe the value above $sore

There are the dipatch and commit we most want to see

Guess you like

Origin blog.csdn.net/qq_37308779/article/details/125904019