vuex是vue.js的官方数据管理架构。
为了实现组件间数据共享的一种机制。
vuex的使用步骤:
- 运行npm install vuex(如果使用vue-cli脚手架创建,在创建的时候选择了安装这里就不用安装了)
- 在store/index.js中导入 vuex
import Vuex from ‘vuex’ (同上,项目创建的时候自动生成了) - 在store/index.js中安装Vuex
Vue.use(Vuex) - 在store/index.js中创建store公共状态对象
const store = new Vuex.Store({
state: { // state 中存放的,就是全局共享的数据,可以把 state 认为 是组件中的 data
count: 0
}
}) - 在main.js中将 创建的 store 挂载到 vm 实例上
new Vue({
router,
store,
render: h => h(App)
}).$mount(’#app’)
访问state中的属性方式一
- 如果想要在组件中访问全局的数据:
this.$store.state.全局数据名称 (这种调用方式vue不推荐)
访问state中的属性方式二
• 按需导入 mapState 辅助函数:
import { mapState } from “vuex”;
• 创建一个computed属性,通过mapState,结合 … 展开运算符,把需要的状态映射到组件的计算属性中:
computed: {
// 通过 展开运算符,把 state中的数据映射为计算属性,这样,能够让自己的计算属性和store中的属性并存
…mapState([“count”])
}
这里注意如果state中的变量和data中的变量重名,优先调用的是data中的变量!!!
修改state中的数据
方法一
方法二
直接通过$store.state.count方式去加
<input type="button" value="+1" @click="$store.state.count++">