vue自学入门-5(vuex state)

vue自学入门-1(Windows下搭建vue环境)

vue自学入门-2(vue创建项目)

vue自学入门-3(vue第一个例子)

vue自学入门-4(vue slot)

vue自学入门-5(vuex state)

vue自学入门-6(vue jsx)

vue自学入门-7(vue style scope)  

vue自学入门-8(vue slot-scope)

同上一节,通过HelloWorld修改一个值,改变App.Vue中显示

实现目标

 

 1、增加一个store文件夹,新建一个idex.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  }
})
export default store

2、修改helloWorld代码如下

import Vue from 'vue'
import store from '../store/index.js'
Vue.use(store)
<template>
  <div class="hello">
    <div @click="add()">点我增加1</div>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  methods: { add () {
    this.$store.state.count += 1
  }},
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

也可以不单独建index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  }
})
Vue.use(store)
<template>
  <div class="hello">
    <div @click="add()">点我增加1</div>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  methods: { add () {
    this.$store.state.count += 1
  }},
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

 

3、修改App.vue代码如下

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  <div>{{count}}</div>
  </div>
</template>

<script>
export default {
  name: 'App',
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

保存成功

 

 3、Vue不推荐直接操作store中对象,推荐使用mutation,修改代码如下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  strict: true,
  state: {
    count: 0
  },
  mutations: {
    add1 (state) {
      state.count += 2
    }
  }
})

export default store

 

 点击就每次增加2

使用mutation方式好处:

1、界面逻辑分离

2、能够通过devtools跟踪

3、不能使用异步函数,防止不确定问题。

 

posted @ 2020-02-23 18:39  zhaogaojian  阅读(302)  评论(0编辑  收藏  举报