为什么用 vuex:组件之间的作用域独立,而组件之间经常又需要传递数据,项目比较小的话传递数据还好,越大的项目,涉及的组件通信就越多、越频繁,此时管理起来就会非常累,而且容易出错,这就是 Vuex 的意义所在。它可以将数据置于单独的一层,并提供给外部操作内部数据的方法。粗俗一点,就这样理解吧。
- $ cnpn install vuex@1.0--save
现在使用 vue1.0 的生态的话都要加上版本号,不是默认都是最新版本,而 vue1.0 只能配合版本 1 来使用。
接下来我们在 vuex 文件夹新建 store.js(初始化的 state 对象) 和 actions.js(定义动作)
store.js 代码如下:
- //引入相关文件
- import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)
- //定义初始化变量
- const state = {
- list: [{
- name: '张三'
- }],
- count: 0
- }
- //定义动作
- const mutations = { //模仿ajax获取新数据后 动态更新data
- GETLIST(state, amount) {
- state.list = amount
- },
- //官方例子,加减
- INCREASE(state, amount) {
- state.count = state.count + amount
- },
- REDUCE(state, amount) {
- state.count = state.count - amount
- }
- }
- export
- default new Vuex.Store({
- state,
- mutations
- })
actions.js 代码如下:
- export const listsCounter = function({
- dispatch,
- state
- },
- list) { //list为调用increment方法所传的值
- dispatch('GETLIST', list)
- }
- export const increaseCounter = function({
- dispatch,
- state
- }) {
- dispatch('INCREASE', 1)
- }
- export const reduceCounter = function({
- dispatch,
- state
- }) {
- dispatch('REDUCE', 1)
- }
最后我们在 main.js 文件引入 store
- import store from './components/vuex/store'
- //Vue中加入store
new Vue({
store,
components: {App}
})
我们需要修改根组件来让应用注意到 store 的存在位置。 [vuex] store not injected. make sure to provide the store option in your root component. 如果没有在根组件引入控制台会提示这个警告
App.vue 文件中引入 store
- import store from './components/vuex/store'export
- default {
- store:
- store
- }
引入完后,我们打开第二章里建的 MenuLeft.vue 文件。我的思路如下图
ok,我们开始吧,引入 store 文件
- template中加入
- import store from '../vuex/store'export
- default {
- components:
- {
- User
- },
- data() {
- return {
- datas: []
- }
- },
- methods: {
- go(el) {
- this.$route.router.go({
- path: el
- })
- },
- },
- store: store,
- vuex: {
- getters: {
- data: state = >state.list,
- //获取我们刚刚在store文件中定义的list数组对象
- countValue: state = >state.count //获取count变量,用于显示加减改变的值
- }
- },
- }
ok,现在可以看看效果了,顺利的话,你应该和下图是一样的
接下我们就开始写方法,动态改变 list 吧,进入 AsideHeade.vue 文件,引入 actions.js
- import {
- listsCounter
- }
- from '../vuex/actions'export
- default {
- data() {
- return {
- ab:
- [{
- name:
- '王五'
- }]
- }
- },
- methods: {
- change() {
- this.setlist(this.ab)
- }
- },
- vuex: {
- actions: {
- setlist: listsCounter
- }
- }
- }
你们可以试试点 看看左侧导航是不是发生改变了,是不是感觉 vuex 还是挺不错的,哈哈。
我们还有一个加减的例子,我想留在大家在看官网的同时实现出来,样式下图。
三篇 vue 项目搭建就完了,相信大家已经可以自己搭建出来了,放出来供大家下来研究。
来源: http://www.cnblogs.com/ychl/p/6122104.html