v3项目的话引入vuex和之前vue2项目的是有点点差别了.

vue3项目的话

1.先创建文件夹

2.在store.js中定义state,等等全局数据

import {createStore} from 'vuex'


const store = createStore({
	state:{//存放状态
		"username":"foo",
		"age":18
	},
	getters: {
	   
	},
	mutations: {
	
	},
	actions: {
	
	},
	modules:{
		
	}
})

export default store

3.在main.js中注册vuex

import App from './App'
import store from '@/store/store.js'
// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App,
	store
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  app.use(store)
  return {
    app
  }
}
// #endif

 

4.使用的话

<template>
	<view>
		
	</view>
</template>

<script lang="ts" setup>
import { onMounted } from "vue";
import store from '../../store/store.js'

	
onMounted(()=>{
	console.log(store.state.username)
})
	
</script>

<style>
	
</style>

和vue2对比的话

主要就是store.js文件的区别(vue2中的使用方法) 这个方法的话放在vue3项目中的话import会报错

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

//实例store并导出
export default new Vuex.Store({
	state: {
	
	},
	mutations: {
		/*......*/
	}
})

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐