vue3 state管理

燕靖
2023-12-01
npm install vuex --save

main.js

:const store = createStore

import {
	createApp
} from 'vue'
import * as VueRouter from 'vue-router';
import {
	createStore
} from 'vuex'

import 'element-plus/dist/index.css'
import ElementPlus from 'element-plus'

import App from './App.vue'
import Product from './products/index.vue'
import Merchands from './merchands/index.vue'
import Apple from './appstore/index.vue'

const routes = [{
		path: '/',
		component: Product
	},
	{
		path: '/m',
		component: Merchands
	},
	{
		path: '/a',
		component: Apple
	},
]
const router = VueRouter.createRouter({
	// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
	history: VueRouter.createWebHashHistory(),
	routes, // `routes: routes` 的缩写
})

const store = createStore({
	state() {
		return {
			count: 0
		}
	},
	mutations: {
		increment(state) {
			state.count++
		}
	}
})

var app = createApp(App);
app.use(router);
app.use(store);
app.use(ElementPlus);

// 屏蔽错误信息
app.config.errorHandler = () => null;
// 屏蔽警告信息
app.config.warnHandler = () => null;

app.mount('#app');

Apple.vue

:useStore

<template>
	<el-card class="box-card">
		<template #header>
			<div class="card-header">
				<span>子组件内容</span>
			</div>
		</template>
		<div>	
		<el-button v-on:click="increment()" type="primary">点击</el-button>
		<label>{{store.state.count}}</label>
		</div>
		<div>
			<h1>{{title1}}</h1>
			<button @click="triggerParentMethod">子窗口触发父窗口绑定的事件</button>
		</div>

		<div>
			<h1>{{productName}}</h1>
			<button @click="changeProductName">改变产品名称</button>
		</div>

	</el-card>

</template>

<script lang="ts">
	import {
		defineComponent,
		toRefs,
		watch,	
		reactive
	} from 'vue'
	import { useStore } from 'vuex'
	
	export default defineComponent({
		props: {
			title1: String
		},
		emits: ['parentRun'],

		setup(props, context) {
			const store = useStore()
			console.log(store);
			watch(
			  () => props.title1,
			  (title1, prevTitle1) => {
			    console.log(`修改前:${prevTitle1}-修改后:${title1}`)
			  }
			)
			const data = reactive({
				productName: "西瓜"
			})

			const triggerParentMethod = () => {
				context.emit("parentRun", "子组件中触发父窗口中的方法")
			}

			const showMe = () => {
				console.log('父窗口ref调用子方法')
			}
			const changeProductName = () => {
				data.productName = "南瓜"
			}
			
			const increment=()=>{
				store.commit('increment');
			}

			return {
				triggerParentMethod,
				showMe,
				changeProductName,
				increment,
				store,
				...toRefs(data)
			}
		}
	})
</script>

<style>
</style>

 类似资料: