Vuex的基本使用
1.安装vuex依赖包
npm install vuex --save
2.导入vuex包(在store.js)
import Vuex from 'vuex'
Vue.use(Vuex)
3.创建store对象(在store.js)
const store = new Vuex.Store({
//state 中存放的就是全局共享的数据
state:{ count:0 }
})
4.将store对象挂载到vue实例中(在App.vue)
new Vue({
el:'#app',
render:h=> h(app),
router,
//将创建的共享数据对象,挂载到Vue实例中
//所有的组件,就可以直接从store中获取全局的数据了‘
store
})
5.使用Vuex共享数据(路由组件)
第一种方法:
<template>
<div>
<p>{{this.$store.state.count}}</p>
//this可以省略
<p>{{$store.state.count}}</p>
</div>
</template>
第二种方法:
<template>
<div>
<p>{{count}}</p> //直接使用count
</div>
</template>
<script>
//从vuex中按需导入mapState函数
import { mapState } from 'vuex'
export default{
data(){
return{}
},
computed:{
...mapState(['count']) //...表示展开运算符,将全局数据映射为当前组件的计算属性
}
}
</script>