vuex

来源:互联网 发布:淘宝卖lol限定皮肤 编辑:程序博客网 时间:2024/05/16 01:15

https://vuex.vuejs.org/

vuex基本概念

  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
  • 状态:数据
    因为组件的状态变化其实就是数据的变化,所以状态 == 数据。
  • vuex : 提供数据的存储规则以及访问规则。
    每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
      1.Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
      2.你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。

应用场景

虽然 Vuex 可以帮助我们管理共享状态,但也附带了更多的概念和框架。这需要对短期和长期效益进行权衡。
如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 global event bus 就足够您所需了。但是,如果您需要构建是一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。

安装

  1. 运行“npm install vuex”或“yarn add vuex”命令。
  2. 在store/index.js中:
    • 引入 import Vuex from ‘Vuex’
    • Vue.use(Vuex)
    • 配置:new Vuex.Store({});
  3. 在main.js中:

    • 引入import Vuex from ‘Vuex’;
    • 使用

      <code>    new Vue({        el: '#app',        router,    //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件        store,        template: '<App/>',        components: { App }    })</code>

核心概念

store

store - 仓库;
  • 用来存储数据;
  • 创建仓库:
        仓库 = new Vuex.Store()

    <code>    import Vue from 'vue';    import Vuex from 'Vuex';    Vue.use(Vuex);    // 创建一个仓库,构造函数接受一个参数,这个参数是一个对象    export default new Vuex.Store({    })</code>
  • 当我们把 仓库 作为属性注入到 Vue 实例中的时候,在 Vue 实例对象下就会多出来一个属性:storethis.store 来访问这个仓库了。
    Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。
    个应用将仅仅包含一个 store 实例。

 1.state

在Store中有一个属性:state,这个就是用来存储全局应用数据。state 和 data 的区别:
  • state:存储全局应用数据
  • data:存储组件内部数据

    <code>    export default new Vuex.Store({        /**         * 状态属性,状态又称为数据         * 用来存储源数据         */        state: {            message: 'Hello Miaov!',            username: 'zMouse',            age: 33,            content: '妙味课堂'        }    })</code>

2.getters

  • getters,其实就是store中state的派生数据,当我们需要从原始数据state中提取一些数据的时候,可以使用getters来处理,他类似组件中的计算属性,在组件中我们可以通过 this.$store.getters来获取这些数据。
  • Getter中的计算属性函数也可以接受一些参数:
    • 第一个参数:store的state对象
    • 第二个参数:store的getters对象

1.在store/index.js中 

export default new Vuex.Store({      state:{}    // 存储计算、派生数据,该数据是由state源数据根据某种条件计算得来的    getters: {        showTodos(state) {            /*            * 因为数据是state派生的,所以我们要去访问state            * */            return state.todos.filter( todo => {                switch (state.type) {                    case '1':                        return todo.done;                        break;                    case '2':                        return !todo.done;                        break;                    default:                        return true;                }            } );        }    },});
  1. 在getters.vue

    <code>    <script>        export default {            data() {                return {                    type: this.$store.state.type                }            }            computed: {                showTodos() {                    return this.$store.getters.showTodos;                }            }        }</code>

3.mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
他类似vue组件中的事件通知,我们要在组件中修改state,不要直接去修改,这样会造成数据的不可维护,统一交由store去修改,在store中有一个专门存放修改state的对象 - mutations,这个对象可以放置用来修改state的方法,然后在组件中通过 commit 提交任务来制定一个mutations来修改state。

1.在store/index.js中

<code>    export default new Vuex.Store({        state:{},        getters:{},        mutations: {            changeType(state, value) {                /*                * 第一个参数:state                * 第二个参数:提交commit的时候传递过来的数据                * */                console.log('changeType', value);                state.type = value;                return true;//即使加了返回值,组件那边得到的还是undefined            }        },    });</code>

2.getters.vue

<code>    <script>        export default {            watch: {                type() {        // 直接是没有问题的,但是,最好不要这样做,为了保证数据的完整,安全,可用,最好不要在组件中直接修改仓库中的state,交给仓库自己去改                    //this.$store.state.type = this.type;                    // 通过出发mutations里面对应的方法来修改state数据                    //this.$store.mutations.changeType(); //这是错的,使用commit提交一个任务来触发执行                    //var result = this.$store.commit('changeType', this.type);                    console.log(result);//返回undefined                }            }        }    </script></code>

4.action

Action 类似于 mutation,不同在于:

  • Action和Mutation最大的一个不同:返回值
    • Mutation处理完成以后不会返回任何结果
  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

如果我们希望store修改完数据以后会返回数据给组件,那么使用actions,否则使用mutations。

1.在store/index.js中

<code>          export default new Vuex.Store({        state:{},        getters:{},        mutations: {},        actions:{                           changeType(store, value) {                store.commit('changeType', value);            }        }               });</code>

1.在getters.vue中,通过dispatch提交返回的值是一个promise对象。

<code>    <script>        export default {            // action:action不是通过commit提交的,而是 dispatch            var result = this.$store.dispatch('changeType', this.type);                //result是promise对象            result.then(function(rs) {                console.log(rs);            })        }    </script></code>

vue devTools

基于node.js开发。

当使用 Vue 时,我们推荐同时在你的浏览器上安装 Vue Devtools,它允许你在一个更加友善的界面中审查和调试你的 Vue 应用。

  • 手动安装(否则要翻墙)

    1. 克隆github的仓库源码
    2. 进入源码目录,运行install命令安装需要的源文件
      1. npm install
      2. yarn install
    3. 运行 npm run build 或者 yarn run build 生成插件
    4. 打开chrome浏览器,进入扩展设置:菜单->更多工具->扩展程序
    5. 进入扩展模式以后,选中开发者模式
    6. 点击”load unpacked extension”->“加载已解压的扩展程序”
  • 应用

axios

  1. 概念

    • axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端。
    • ajax库,封装ajax

    本身具有以下特征:
      从浏览器中创建 XMLHttpRequest
      从 node.js 发出 http 请求
      支持 Promise API
      拦截请求和响应
      转换请求和响应数据
      取消请求
      自动转换JSON数据
      客户端支持防止 CSRF/XSRF

  2. 安装:npm install axios –save

  3. get请求
    后端:app.js

    <code>    const express = require('express');    const bodyParser = require('body-parser');          const app = express();    app.use( bodyParser.json() );    app.get('/', (req, res) => {      res.json(taskList);    })</code>
  4. post请求


    app.post('/add', (req, res) => {
    taskList.push({
    title: req.body.title,
    done: false
    });
    res.json({
    code: 0,
    message: '添加成功'
    })
    });

前端:store/index.js

<code>    export default new Vuex.Store({        state:{},        getters:{},        mutations:{},        actions: {        updateTaskList(store) {            axios.get('http://localhost:9090/')                .then( res => {//                this.$store.state.taskList = res.data;                    store.commit('updateTaskList', res.data);                } )        },        addNewTask(store, data) {            axios.post('http://localhost:9090/add', {                title: data.title            }).then(res => {                store.commit('addNewTask', {                    title: data.title,                    done: false                });                //将后端返回信息提供给组件,可是组件弹出结果信息                return Promise.resolve(res)            })        }}</code>

todoList

有时候,你可能想在某个组件的根元素上监听一个原生事件。可以使用 v-on 的修饰符 .native。例如:

原创粉丝点击