Vuex的基本概念、项目搭建以及入坑点

前言:Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化.

Vuex的四大核心

1.state 驱动应用的数据源

2.mutations 基因突变 类如C# 属性get set

3.actions 行为

4.getters 读取器

上图中绿色虚线包裹起来的部分就是Vuex的核心, state 中保存的就是公共状态, 改变 state 的唯一方式就是通过 mutations 进行更改. 可能你现在看这张图有点不明白, 等经过本文的解释和案例演示, 再回来看这张图, 相信你会有更好的理解.

如何引入Vuex?

1.npm install vuex

2.装好了之后,在全局上去使用你的Vuex

3.创建Store对象,最好在src创建一个store这样的文件夹然后创建index.js

4.在main.js中注册使用

import Vuex from 'vuex'

Vue.use( Vuex );

const store = new Vuex.Store({

  //待添加

})

new Vue({

  el: '#app',

  store,

  render: h => h(App)

})

为了讲解Vuex,我们做了一个项目,这个项目需要连接apicloud,异步操作使用了axios以及样式bootstrap,其中包括了登录注册以及其中的父组件向子节点传值等,我们给项目安装相关的modules

npm install bootstrap
npm install axios

router.js

import Vue from 'vue'

import Router from 'vue-router'

Vue.use(Router)

export default new Router({

 routes: [

  {

   path: '/',

   name: 'index',

   component:()=>import('../views/index.vue')

  },

  {

   path:'/detail/:id',

   name:'detail',

   component:()=>import ('../views/detail.vue')

  },

  {

   path:'/login',

   name:'login',

   component:()=>import ('../views/login.vue')

  },

  {

   path:'/register',

   name:'register',

   component:()=>import ('../views/register.vue')

  }

 ]

})

store.js

我们来上述代码中来讲解其中vuex的奥秘,State就是所有组件提出来的data,用于所有组件公共数据,而其中mutations就像C#中get\set,属性赋值器,其中方法的两个参数除了state只能带一个参数。

actions是操作数据的方法,说过说你的actions中需要改变state中的数据,那么必须要通过commit关键字去提交给mutations,还有一点就是actions中很多操作都是关于异步处理的,最关键就是它是操作state数据的,那getters是什么呢?它是组件访问vuex的入口,里面写好了方法去操作,它也是过滤器,就像程序中的三层架构BLL.

main.js

// The Vue build version to load with the `import` command

// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from 'vue'

import App from './App'

import router from './router'

import boostrap from 'bootstrap/dist/css/bootstrap.css'

import store from './store/index.js'

Vue.config.productionTip = false

/* eslint-disable no-new */

new Vue({

 el: '#app',

 router,

 store,//在全局对象上加载仓库

 components: { App },

 template: '<App/>'

}) 

两个组件

import Vue from 'vue'
import Vuex from 'vuex'
import API from '../utils/api.js'

var api = new API('goods')
var userApi = new API('userinfo');

Vue.use(Vuex);

const state = {
  user: null,
  products: []
}
const mutations = {
  //加载产品数据
  INIT_PRODUCTS(state, data) {
    state.products = data;
  },
  SET_LOGIN_USER(state, u) {
    state.user = u;
  }
}
const actions = {
  LOAD_PRODUCTS({ commit }) {
    api.Select().then(res => {
      commit('INIT_PRODUCTS', res.data);
    })
  },
  LOGIN({ commit }, user) {
    return userApi.Select().then(res => {
      let users = res.data;//所有的用户
      for (let u of users) {
        if (u.name == user.name && u.password == user.password) {
          commit('SET_LOGIN_USER', u);
          return u;
        }
      }
    })
  },
  REGISTER({ commit }, user) {
    return userApi.Insert(user).then(res => {
      console.log(res.data);
      return 'OK';
    }).catch(err => {
      return err;
    })
  }

}
const getters = {
  ALL_PRODUCTS(state) {
    return state.products;
  },
  GET_PRODUCT_BYID: (state) => function (id) {
    //遍历 is == id
    for (let p of state.products) {
      if (p.id == id) {
        return p;
      }
    }
    return null;
  }
}

//仓库
const store = new Vuex.Store({
  state: state,
  mutations: mutations,
  actions: actions,
  getters: getters
})
export default store;

navbar.vue

<template>
   <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
      <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >购物车</a>
      <ul class="navbar-nav ml-auto">
        <li class="nav-item active dropdown" v-if="user!==null">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" @click="showDropdown=!showDropdown">欢迎你:{{user.name}} </a>
          <div class="dropdown-menu show">
            <a class="dropdown-item" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >我的订单</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" >注销</a>
          </div>
        </li>
        <li class="nav-item active" style="margin-right:5px" v-if="user===null">
          <router-link class="nav-link btn btn-warning btn-sm" style="color:#fff" to="/login">登录</router-link>
        </li>
        <li class="nav-item active" v-if="user===null">
          <router-link class="nav-link btn btn-danger btn-sm" style="color:#fff" to="/register">注册</router-link>
        </li>
      </ul>
    </div>
  </nav>
</template>

<script>
export default {
  data(){
    return{
      showDropdown:false
    }
  },
  computed:{
    user(){
      return this.$store.state.user;
    }

  }
}
</script>

product.vue 该组件用于显示商品的详细信息

<template>
  <div class="card">
    <img class="card-img-top" src="../../assets/logo.png" alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">{{product.name}}</h5>
      <p class="card-text">{{product.description===null?"暂无描述":product.description}}</p>
      <p>价格: {{product.price}}</p>
      <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="btn btn-warning float-left" @click="goDetail">查看详情</a>
      <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="btn btn-primary float-right">加入购物车</a>
    </div>
  </div>
</template>

<script>
export default {
  props:['product'],
  methods:{
    goDetail(){
      console.log(this.product.id);
      this.$router.push(`/detail/${this.product.id}`);
    }
  }
}
</script>

程序入口APP.vue

<template>
 <div id="app">
  <nav-bar></nav-bar>
  <router-view></router-view>
 </div>
</template>

<script>
import NavBar from './views/components/navbar'
export default {
  name: 'App',
  components:{NavBar}
}
</script>

注册:通过 this.$store.dispatch去调用actions中的方法,其中有趣的是commit的参数竟然被方法名给..这个以后在思考。。

<template>
  <div class="container">
    <div class="row">
      <div class="card" style="margin:50px auto;width:400px">
        <div class="card-body">
          <h5 class="card-title">注册</h5>
          <hr>
          <div class="form-group">
            <label for="">用户名</label>
            <input type="text" class="form-control" v-model="user.name">
          </div>
          <div class="form-group">
            <label for="">真实姓名</label>
            <input type="text" class="form-control" v-model="user.realname">
          </div>
          <div class="form-group">
            <label for="">密码</label>
            <input type="password" class="form-control" v-model="user.password">
          </div>
          <div class="form-group">
            <button class="btn btn-primary btn-block" @click="register">注册</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      user:{
        name:'',
        realname:'',
        password:''
      }
    }
  },methods:{
    register(){
      this.$store.dispatch('REGISTER',this.user).then(res=>{
        if(res=="OK")
          this.$router.push('/index');
      })
    }
  }
}
</script> 

登录

<template>
  <div class="container">
    <div class="row">
      <div class="card" style="margin:50px auto;width:400px">
        <div class="card-body">
          <h5 class="card-title">登录</h5>
          <hr>
          <div class="form-group">
            <label for="">用户名</label>
            <input type="text" class="form-control" v-model="user.name">
          </div>
          <div class="form-group">
            <label for="">密码</label>
            <input type="password" class="form-control" v-model="user.password">
          </div>
          <div class="form-group">
            <button class="btn btn-primary btn-block" @click="login">登录</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      user:{
        name:'',
        password:''
      }
    }
  },
  methods:{
    login(){
      this.$store.dispatch('LOGIN',this.user).then(res=>{
        console.log(res);
        if (res){
          this.$router.push('/')
        }
      })
    }
  }
}
</script>

主页面

<template>
  <div class="container">
    <h1>商品列表</h1>
    <div class="row">
       <div class="col-md-4" v-for="p in products" :key="p.id">
        <!-- 传递商品信息到子组件 -->
        <product-card :product="p"></product-card>
      </div>
    </div>
  </div>
</template>

<script>
import ProductCard from './components/product.vue'
export default {
  components:{ProductCard},
  computed:{
    products(){
      return this.$store.getters.ALL_PRODUCTS;
    }
  },
  created(){
    this.$store.dispatch('LOAD_PRODUCTS');
  }
}
</script>

本文结语知识总结:

获取url中的参数

let id = this.$route.params.id;
this.details = this.$store.getters.GET_PRODUCT_BYID(id);

有的小伙伴在复制我的代码运行报错,说什么未初始化;一定要在index.vue添加这个代码,LOAD_PRODUCTS给数据初始化

created(){
    this.$store.dispatch('LOAD_PRODUCTS');
  }

跳转路由

this.$router.push('/')

ApiClound万能帮助类

import crypto from 'crypto'   // 加密
import axios from 'axios'
class API {
  constructor(classname){
    this.api = `https://d.apicloud.com/mcm/api/${classname}`;
    let ID = '';
    let KEY = '';
    let now = Date.now(); //当前时间
    let sha1 = crypto.createHash('sha1');
    sha1.update(ID + "UZ" + KEY + "UZ" + now);
    axios.defaults.headers["X-APICloud-AppId"] = ID;
    axios.defaults.headers["X-APICloud-AppKey"] = sha1.digest('hex') + "." + now;
  }

  Select(){
    return axios.get(this.api);
  }
  Insert(obj){
    return axios.post(this.api,obj);
  }
  Update(id,obj){
    // RESTFUL API
    return axios.put(this.api+`/${id}`,obj);
  }
  Delete(id){
    return axios.delete(this.api + `/${id}`);
  }
}

export default API;

还有同学问我父组件和子组件如何传值?

在父页面引用的地方以":"表示的值都可以在子页面的props获取到

<template>
<div>
  <h3>图书管理</h3><hr>
  <div class="row">
    <div class="col-md-4 col-sm-4" v-for="b in books" :key="b.id">
      <book-detail @abc="xyz" :Book="b" :MSG="abc"></book-detail>
    </div>
  </div>
</div>
</template>
<script>
  import BookDetail from './components/BookDetails.vue'
  export default{
    components:{BookDetail},
    data(){
      return {
        abc:'heheda',
        books:[{
          id:1,
          name:'7天 JAVA 从入门到放弃',
          text:'到底是人性的扭曲,还是道德的沦丧. 青年男子为何突然脱发,中年男人为何删库跑路。',
          price:20,
          img:'img2.jpg',
          showHehe:true
        },{
          id:2,
          name:'7天 C# 从入门到自杀',
          text:'到底是人性的扭曲啊,还是道德的沦丧啊. 祖国的花朵为何自杀。',
          price:20,
          img:'../../static/img2.jpg',
          showHehe:false
        }]
      }
    },
    methods:{
      xyz(bid){
        alert(bid);
      }
    }
  }
</script>

在子页面中可以这么搞

<script>
export default{
  props:["Book","MSG"],
  created(){
    console.log(this.Book.name);
  },
  methods:{
    select(id){
      this.$emit('abc',id);
    },
    detail(bid){
      this.$router.push(`/admin/Details/${bid}`);
    }
  }
}
</script>

而其中的$emit是可以调用父页面的方法的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Vue CLI 3搭建vue+vuex最全分析(推荐)

    一.介绍 Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统.有三个组件: CLI:@vue/cli 全局安装的 npm 包,提供了终端里的vue命令(如:vue create .vue serve .vue ui 等命令) CLI 服务:@vue/cli-service是一个开发环境依赖.构建于 webpack和 webpack-dev-server之上(提供 如:serve.build 和 inspect 命令) CLI 插件:给Vue 项目提供可选功能的 npm 包 (如:

  • 详解vue+vuex+koa2开发环境搭建及示例开发

    写在前面 这篇文章的主要目的是学会使用koa框架搭建web服务,从而提供一些后端接口,供前端调用. 搭建这个环境的目的是: 前端工程师在跟后台工程师商定了接口但还未联调之前,涉及到向后端请求数据的功能能够走前端工程师自己搭建的http路径,而不是直接在前端写几个死数据.即,模拟后端接口. 当然在这整个过程(搭建环境 + 开发示例demo)中,涉及到以下几点知识点. 包括: koa2的知识点 node的知识点 跨域问题 fetch的使用 axios的使用 promise的涉及 vuex -> st

  • mpvue+vuex搭建小程序详细教程(完整步骤)

    本文介绍了mpvue+vuex搭建小程序详细教程(完整步骤),分享给大家,具体如下: 源码 mpvue-vuex-demo 构成 1.采用mpvue 官方脚手架搭建项目底层结构 2.采用Fly.js 作为http请求库 3.引入mpvue-router-patach,以便在mpvue小程序中能使用vue-router的写法 目录结构 ├── src // 我们的项目的源码编写文件 │ ├── components // 组件目录 │ ├── common //静态资源 │ │ └── font

  • Vuex的基本概念、项目搭建以及入坑点

    前言:Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化. Vuex的四大核心 1.state 驱动应用的数据源 2.mutations 基因突变 类如C# 属性get set 3.actions 行为 4.getters 读取器 上图中绿色虚线包裹起来的部分就是Vuex的核心, state 中保存的就是公共状态, 改变 state 的唯一方式就是通过 mutations 进行更改. 可能你现在

  • 浅谈angular4实际项目搭建总结

    前言 接到一个pc端后台项目,还会加入两个安卓同事一起学习和做这个项目,需要带一下他们. 既ng1之后,我就没怎么有过其它后台框架的实际项目经验了,期间用的移动端框架也并非vue.angular系列.react,包括es6.webpack等也都并不熟悉. 公司一个其它后台项目使用了vue,偶尔我会维护一下但是总体来说对体系不熟悉. 一直比较喜欢angular,应该是有过ng1框架搭建的经验的原因(前面也有写过博客),学习过ng2和ng4的官方demo,总的来说照着抄写一遍意义不大,必须要用于实际

  • 基于mpvue的小程序项目搭建的步骤

    前言 mpvue 是美团开源的一套语法与vue.js一致的.快速开发小程序的前端框架,按官网说可以达到小程序与H5界面使用一套代码.使用此框架,开发者将得到完整的 Vue.js 开发体验,同时为 H5 和小程序提供了代码复用的能力.如果想将 H5 项目改造为小程序,或开发小程序后希望将其转换为 H5,mpvue 将是十分契合的一种解决方案. Mpvue官网:http://mpvue.com/ demo地址 :https://github.com/ccwyn/mpvuedemo/tree/mast

  • 基于 Vue 的 Electron 项目搭建过程图文详解

    Electron 应用技术体系推荐 目录结构 demo(项目名称) ├─ .electron-vue(webpack配置文件) │ └─ build.js(生产环境构建代码) | └─ dev-client.js(热加载相关) │ └─ dev-runner.js(开发环境启动入口) │ └─ webpack.main.config.js(主进程配置文件) │ └─ webpack.renderer.config.js(渲染进程配置文件) │ └─ webpack.web.config.js ├

  • vue3.0 项目搭建和使用流程

    最近在重构一个老项目,领导要求使用新的技术栈.好吧,是时候秀一波我新学的vue3.0了. 不多bb,开始我的表演...(以下只是我自己个人的理解和使用习惯,仅供参考哦) 一:项目搭建 1. 可以自己配置vite,但是为了节省时间,我就使用脚手架直接搭建.(有兴趣可以研究一下vite,还是很香的) 2. 项目生成:iTerm下: vue create myproject 之后根据自己的要求选择不同的配置 选择我们需要的3.x 之后按照要求配置一下router,已经pack.json ... 然后n

  • vite+vue3+element-plus项目搭建的方法步骤

    使用vite搭建vue3项目 通过在终端中运行以下命令,可以使用 Vite 快速构建 Vue 项目. $ npm init vite-app <project-name> $ cd <project-name> $ npm install $ npm run dev 引入Element Plus 安装Element Plus: npm install element-plus --save main.js中完整引入 Element Plus: import { createApp

  • vue3.0 项目搭建和使用流程

    目录 一:项目搭建 二: 目录结构 三: Composition Api 四: 基本使用: 最近在重构一个老项目,领导要求使用新的技术栈.好吧,是时候秀一波我新学的vue3.0了. 不多bb,开始我的表演...(以下只是我自己个人的理解和使用习惯,仅供参考哦) 一:项目搭建 1. 可以自己配置vite,但是为了节省时间,我就使用脚手架直接搭建.(有兴趣可以研究一下vite,还是很香的) 2. 项目生成:iTerm下: vue create myproject 之后根据自己的要求选择不同的配置 选

  • 从零搭建一个vite+vue3+ts规范基础项目(搭建过程问题小结)

    目录 项目初始化 安装router和pinia 安装ESlint eslint的vue规则需要切换 安装prettier 安装stylelint 安装husky 安装commitlint 总结 参考: 最近时间总算是闲了下来,准备着手搭建一个基础模板,为后面新项目准备的,搭建过程中遇到不少问题,现在总结下来给大家使用. 项目初始化 本项目已vite开始,所以按照vite官方的命令开始.这里使用的命令行的方式来搭建基础项目: yarn create vite my-vue-app --templa

  • 一个基于vue3+ts+vite项目搭建初探

    目录 前言 环境准备 使用Vite快捷搭建 使用npm 使用yarn 安装依赖 启动项目 修改vite配置文件 找到根目录vite.config.ts文件打开 集成路由 集成Vuex 添加element ui 集成axios 集成Sass Vue3 使用 总结 前言 基于Vue3已经成为默认版本,目前的项目暂时还没有使用过vue3开发和最近有一个全新的新项目的基础下,使用vue3开发项目,必然是未来的一个趋势 下面记录一下怎么使用Vue3 + ts + vite 从0开始搭建一个项目 环境准备

  • Python之Web框架Django项目搭建全过程

    Python之Web框架Django项目搭建全过程 IDE说明: Win7系统 Python:3.5 Django:1.10 Pymysql:0.7.10 Mysql:5.5 注:可通过pip freeze查看已安装库版本信息. Django 是由 Python 开发的一个免费的开源网站框架,可以用于快速搭建高性能,优雅的网站! Django 特点 强大的数据库功能 用python的类继承,几行代码就可以拥有一个丰富,动态的数据库操作接口(API),如果需要你也能执行SQL语句. 自带的强大的后

随机推荐