1、需求分析
当一些组件可能使用的很频繁,但是组件中却又有着一些不固定的属性,而插槽又不能满足了我们的需要
2、应用场景
比如在nav导航中,可能要需要随时修改到标题的名字,我们就可以用vuex 来管理一些全局状态,这时候不管组件嵌套的有多深
我们都可以直接调用或修改到
3、上代码(注:要先安装vuex插件的,官方API有说明)
一、在src中新建一个文件夹单独管理,然后在里面新建index.js
index.js 里导入vuex 写好需要的功能后导出
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
title:'',
},
mutations: {
setTitle (state,name) {
// 变更状态
this.state.title=name
}
}
})
export default store
main.js 导入store使用
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.use(store)
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
app.vue 监听路由改变后修改标题
export default {
mounted() {
this.$store.commit("setTitle", this.$route.meta.title);
},
watch: {
$route(to, from) {
this.$store.commit("setTitle", to.meta.title);
}
}
};
navbar组件 直接绑定使用
<template>
<div id="NavBar">
<van-nav-bar
:title="$store.state.title"
left-text="返回"
right-text="按钮"
left-arrow
@click-left="onClickLeft"
@click-right="onClickRight"
/>
</div>
</template>
注1:在调用mutations的时候不像getters里面方法能直接调 需要调用 commit()来调用
第一个参数是你在mutations定义的方法名,第二个是自定义的参数
如果参数多,推荐另外一种传参方式 如:
this.$store.commit({
type:"setTitle",
name:'主页'
})
注2:为什么不直接修改state下的属性,而要多绕一圈用mutations里的方法来提交
直接修改其时是可以的,而且会简便很多,但是官方关不推荐这样做,因为你相当于绕过了vuex的监听机制
当你在调试代码时,也无法查看到具体过程的状态。