第一次写技术文章仍是蛮激动的,先从哪里下手好呢?先说说vuex是什么吧,官方文档是这么解释的:vue
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的全部组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。git
我理解过来就是:github
状态的储存站以及全局数据(可能会有些误差)
怎么在vue项目中使用vuex呢
首先安装vuex
npm istall vuex
而后在main.js里引入vuexnpm
//main.js import Vuex from 'vuex' Vue.use(Vuex)
每个 Vuex 应用的核心就是 store(仓库)。"store" 基本上就是一个容器,它包含着你的应用中大部分的状态(即 state)segmentfault
在例子中,直接建立了一个store.js文件来保存仓库的信息:app
const store = { state: { starList: [{ title: "掘金", href: "https://gold.xitu.io/" },{ title: "GitHub", href: "https://github.com/" },{ title: "SegmentFault", href: "https://segmentfault.com/" }] } } module.exports = store
在main.js中引入它,并初始化Vuex.Store:函数
//main.js import stores from './store' const store = new Vuex.Store(stores) new Vue({ el: '#app', store, template: '<App/>', components: { App } })
state做为store的惟一数据源而存在,在组件里可使用this.$store.state
来获取,可是这个数据是只读的,没法直接经过给this.$store.state
赋值来达到赋值的效果,这时就轮到mutation出场了.工具
mutation是惟一能更改store中的状态(state)的方法,这个至关于事件,每一个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是咱们实际进行状态更改的地方,而且它会接受 state 做为第一个参数flex
由于是收藏夹demo,因此应该有一个添加的功能,给store加上一个能够添加item的方法:
//store.js mutations: { addStarList(state,obj) { state.starList.push(obj) } }
好了,如今store已经基本完成,接下来就是组件里如何使用这个store了
在子组件中:
<template> <div class="list"> <input type="text" name="title" v-model:value="name" placeholder="名字"> <input type="text" name="href" v-model:value="href" placeholder="href"> <button type="button" @click="add(name,href)">添加</button> <h2>个人收藏</h2> <ul class="star-list"> <li class="item" v-for="item of starList"> <a :href="item.href">{{item.title}}</a> </li> </ul> </div> </template> <script> import {mapState,mapMutations} from 'vuex' export default { name: 'hello', data () { return { name: '', href: '' } }, computed: { ...mapState([ 'starList' ]) }, methods: { ...mapMutations([ 'addStarList' ]), add(name,href) { console.log(name,href); this.$store.commit('addStarList',{ title: name, href: href }) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> ul,li { list-style: none; margin: 0; padding: 0; } .star-list { display: flex; /*flex-direction: row; flex-wrap: wrap;*/ flex-flow: row wrap; justify-content: space-between; align-items: center; } .item { text-align: center; width: 30%; margin-bottom: 20px; } .item a { text-align: center; text-decoration: none; color: #367; font-size: 18px; } </style>
用v-module绑定了表单的值,这样才能将输入的值更新。
在这里解释一下mapState以及mapMutation
mapState 当一个组件须要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,咱们可使用
mapState 辅助函数帮助咱们生成计算属性,让你少按几回键:
mapState让咱们能够不用再写this.$store.state.状态名 来获取状态,而是能够直接使用状态名获取
你能够在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations
辅助函数将组件中的 methods 映射为 store.commit 调用(须要在根节点注入 store)。
mapMutation是一个辅助函数,让咱们不须要再写繁琐的this.$store.commit('functionName')来触发事件,而是能够直接的使用functionName()
主要代码:Demo