Vuex使用
0.准备部分
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store';
Vue.config.productionTip = false
//js中想调用vuex的数据案例
console.log(store.state.str+'main.js')
store.commit('btn');
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode:'history',
base:process.env.BASE_URL,
routes:[{
path:'/',
name:'home',
component:()=>import('./components/Home')
},{
path:'/Page1',
name:'page1',
component:()=>import('./components/Page1')
},{
path:'/Page2',
name:'page2',
component:()=>import('./components/Page2')
}
]
})
1.开搞!
store=>index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
state:{
str:'你好呀',
a:1,
b:2
},
getters:{
setStr(state){
return state.str+'拿到了吗'
}
},
mutations:{
btn(state){
alert(state.str)
},
change(state,newstr){//改值
state.str=newstr;
}
}
})
export default store
home.vue
<template>
<div>
home
<!-- 上面不加this、下面都加 -->
<!-- 从vuex取值方法一 -->
{{$store.state.str}}<br/>
------------------------------<br/>
<!-- 方法二 -->
{{str}} {{a}} {{b}}
getters:{{setStr}}<br/>
<button @click="btn">点我</button>
<button @click="run">点我2</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations} from 'vuex' //方法二
export default {
name:'Home',
computed:{//方法二
...mapState(['str','a','b']),
...mapGetters(['setStr'])
},
methods:{
...mapMutations(['btn','change']),
// 改vux值
run(){
this.change('干啥');
}
}
}
</script>
2种方法调用store值:
方法一:上文{{$store.state.str}},在下文js部分的话要加上this
方法二:下文
import {mapState,mapGetters,mapMutations} from ‘vuex’
computed:{//方法二
…mapState([‘str’,‘a’,‘b’]),
…mapGetters([‘setStr’])
methods:{
…mapMutations([‘btn’,‘change’])}
上文直接{{str}}{{setStr}}
改值不能直接改、要通过mutations方法提交该值!因为vuex是单数据流!
在index.js中
change(state,newstr){//改值
state.str=newstr;
在home.vue
methods:{
…mapMutations([‘btn’,‘change’]),
// 改vux值
run(){
this.change(‘干啥’); }}
点击button2后(修改值):
面试题补充:
1.Vuex有哪些属性?
state、getters、mutations、actions、modules
state 类似于组件中data,存放数据
getters类型于组件中computed
mutations 类似于组件中methods//同步的方法
actions 提交mutations的
modules 把以上4个属性再细分,让仓库更好管理
2.Vuex中的mutaitons和actions区别
mutaitons : 都是同步事物
actions : 可以包含任意异步操作
***在调试中就看出来vue devtool
3.Vuex如何做持久化存储
Vuex本身不是持久化存储
- 使用localStorage自己写
- 使用vuex-persist插件