首页

关于Vuex的全家桶状态管理(一)

seo达人

如果您想订阅本博客内容,每天自动发到您的邮箱中, 请点这里

1:安装

 npm install vuex --save
    
  • 1

2: 在main.js 主入口js里面引用store.js

import Vue from 'vue' import App from './App' import router from './router' import store from './vuex/store' //引用store.js Vue.config.productionTip = false //阻止在启动时生成生产提示 //vue实例 new Vue({
 el: '#app',
 router,
 store, //把store挂在到vue的实例下面 template: '<App/>',
 components: { App }
})
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3:在store.js里引用Vuex

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //注册Vuex // 定义常量  如果访问他的话,就叫访问状态对象 const state = {
  count: 1 } // mutations用来改变store状态, 如果访问他的话,就叫访问触发状态 const mutations = { //这里面的方法是用 this.$store.commit('jia') 来触发 jia(state){
    state.count ++
  },
  jian(state){
    state.count --
  },
} //暴露到外面,让其他地方的引用 export default new Vuex.Store({
  state,
  mutations
})
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

4:在vue组件中使用

使用$store.commit(‘jia’)区触发mutations下面的加减方法

<template> <p class="hello"> <h1>Hello Vuex</h1> <h5>{{$store.state.count}}</h5> <p> <button @click="$store.commit('jia')">+</button> <button @click="$store.commit('jian')">-</button> </p> </p> </template> <!-- 加上scoped是css只在这个组件里面生效,为了不影响全局样式 --> <style scoped> h5{ font-size: 20px; color: red; } </style>
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

这里写图片描述

5:state访问状态对象

使用computed计算

<template> <p class="hello"> <h1>Hello Vuex</h1> <h5>{{count}}</h5> <p> <button @click="$store.commit('jia')">+</button> <button @click="$store.commit('jian')">-</button> </p> </p> </template> <script> import {mapState} from 'vuex' export default{
  name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用 // 方法一 // computed: { //  count(){ //   return this.$store.state.count + 6 //  } // } // 方法二 需要引入外部 mapState computed:mapState({
   count:state => state.count + 10 }) // ECMA5用法 // computed:mapState({ //  count:function(state){ //   return state.count //  } // }) //方法三 // computed: mapState([ //  'count' // ]) } </script>
蓝蓝设计www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、 网站建设 平面设计服务

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档