vuex
是vue
的全局状态管理模式,定义在vuex
中的值可在整个项目的组件中使用
npm install vuex --save
store/index.js
import { createStore } from 'vuex' export default createStore({ /** * 集中存储组件的状态 */ state: { name: '' }, /** * 改变数据方法的集合 */ mutations: { }, /** * 改变mutations,不直接变更状态 */ actions: { }, /** * 可以将store进行功能拆分,分割成不同的模块 */ modules: { } })
import store from '@/store/index' console.log(store.state.name)
vuex
全局变量的改变做路由跳转,路由跳转页面由全局状态改变的参数决定,效果如下:store/index.js
import { createStore } from 'vuex' export default createStore({ /** * 集中存储组件的状态 */ state: { name: '', // 跳转组件的name }, /** * 改变数据方法的集合 */ mutations: { changeView (state, name) { state.name = name } }, /** * 改变mutations,不直接变更状态 */ actions: { }, /** * 可以将store进行功能拆分,分割成不同的模块 */ modules: { } })
App.vue
<template> <div> <router-view/> </div> </template> <script> import router from '@/router' import store from '@/store/index' import { watch, computed } from 'vue' export default { name: 'App', /** * 监听vuex中的name属性做路由跳转 */ setup (props, context) { const changedName = computed(() => store.state.name) watch(changedName, (newVal, oldVal) => { router.push({ name: newVal }) }) } } </script>
home.vue
<template> <div>首页</div> <img @click="toDetail" src="@/assets/logo.png" style="width: 100%;"/> </template> <script> import store from '@/store/index' export default { name: 'home', components: { }, methods: { toDetail (event) { // 改变全局状态变量 store.commit('changeView', 'Detail') } } } </script>
detail.vue
<template> <div>详情页</div> </template>
store/index.js
state: { name: '' }, mutations: { changeView (state, name) { state.name = name } }
home.vue
// store.commit 传参方式1 store.commit('changeView', 'Detail')
store/index.js
state: { name: '' }, mutations: { changeView1 (state, payload) { state.name = payload.name console.log(payload) } }
home.vue
// store.commit 传参方式2 store.commit({ type: 'changeView1', name: 'Detail' })
store/index.js
state: { params: {} }, mutations: { changeView2 (state, payload) { state.params = payload.params console.log(payload) } }
home.vue
// store.commit 传参方式3 store.commit('changeView2', { name: 'Detail' })