vuex及axios的get方法获取数据

vue全家桶:vue + router + vuex构成vue全家桶,更能体现MVVM;

M:vuex,管理数据;VM:view-router,路由;V:vue,页面;

  • 1.vuex安装

npm install axios
  • 2.导入

  • 3.axios的get方法获取数据

<template>
    <div id="app">
        <div id="nav">
            <router-link to="/">Home</router-link> |
            <router-link to="/about">About</router-link>
        </div>
        <router-view />
    </div>
</template>
<!-- 1. 安装:npm install axios,导入:import axios from 'axios' -->
<!-- 2.将axios.get请求方法放入mounted中,根据后台提供修改get('/user?ID=12345')
  引号中的路径名,console.log(response.data)获取后台数据(在浏览器控制台获取data数据)-->
<!-- 3.如何将获取后台数据存在vuex中:
  3.1.放在state中:状态管理与数据属性有关,state是对象,可存放一些数据,
  在state中定义allDatas空数组;store挂载在实例化对象vue上,
  之后就可以通过this.$store.state.allDatas就可以拿到数组,response.data赋值给他 -->
  <!-- 4.this指向的作用域问题:axios.get上边的this可以拿到当前组件对象,在function里边this的拿不到, 
与作用域有关,解决:var _this = this,axios.get上边的this赋值给_this,
下边使用_this.$store.state.allDatas = response.data;-->
<!-- 5.以上可以拿到allDatas数组,即各个组件就可以使用数据,以home组件为例; -->
<script>
import axios from 'axios'
export default {
    name: 'App',
    data() {
        return {

        }
    },
    // 发送ajax请求,response返回响应,response.data拿到数据,之后要放入vuex的state中,
    // 然后自定义了一个变量存储allDatas,然后各个组件都可以拿到他通过this.$store.state.allDatas;
    mounted() {
      console.log(this)
      var _this = this 
        axios.get('http://127.0.0.1:8080/api/comments/')
            .then(function(response) {
                // console.log(response.data);
                console.log(this)
                _this.$store.state.allDatas = response.data;
            })
            .catch(function(error) {
                console.log(error);
            });

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

#nav {
    padding: 30px;
}

#nav a {
    font-weight: bold;
    color: #2c3e50;
}

#nav a.router-link-exact-active {
    color: #42b983;
}
</style>

home组件

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <!-- 1.遍历数组,如果直接将this.$store.state.allDatas写入li标签中过于臃肿,
    可以使用computed计算属性,定义getAllDatas方法, computed监听计算属性,
    即后续allDatas每添加一条数据,数组就增加一条,就立马遍历,实时监听;
    2.以item.title为例,                                                  
    3.往后端添加一条数据,即数据库多了一条数据,后端会返回一个响应,拿到这个响应重新对allDatas进行操作;
    4.allDatas变化,getAllDatas计算属性(计算vuex中state属性),之后直接渲染进来(至li标签中,通过getAllDatas),
    然后自动遍历;-->
    <ul>
      <li v-for = '(item,index) in getAllDatas'>
        {{item.title}}
      </li>
    </ul>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'home',
  components: {
    HelloWorld
  },
  computed:{
    getAllDatas(){
      return this.$store.state.allDatas;
    }
  }
}
</script>
原文地址:https://www.cnblogs.com/hudaxian/p/14447694.html