90 vuex axios

主要内容:https://www.cnblogs.com/GGGG-XXXX/articles/9467325.html

1 vuex

  a 定义: 专门为vue.js设计的集中式状态管理架构

    可以把它理解成一个仓库, 可以共享给其他组件使用.

  b 下载和使用

    下载: npm install vuex

    使用: 在mian.js中 :

      import vuex from 'vuex' , Vue.use(vuex)

      实例化store实例

import Vue from 'vue'
import App from './App'
import router from './router'
import vuex from 'vuex'

Vue.use(vuex)

Vue.config.productionTip = false

const store = new vuex.Store({
    state: {
      show: false,
    }
});

    解耦: 把它写在一个单独的文件里:

import Vue from 'vue'
import Vue_x from "vuex"

Vue.use(Vue_x);

export default  new Vue_x.Store({
   state: {
      show: false,
    },
});

  state : 需要共享的数据

扫描二维码关注公众号,回复: 4087744 查看本文章

  getter: 从state取出的数据做出进一步的简单的计算(进行二次处理)

  mutation: 更改vuex中的store中的状态的唯一方法就是提交mutation

组件中的内容:

<template>
    <div>
      <h1>这是免费课程页面</h1>
      {{name}}
      {{new_name}}
      <button @click="my_click">点我改变数据</button>
    </div>
</template>

<script>
    export default {
        name: "Freecourse",
        data(){
          return {
            // name:this.$store.state.name,
            new_name:this.$store.getters.new_s
          }
        },
      methods:{
          my_click:function () {
            //向仓库提交数据,告诉仓库我要改编数据了
            this.$store.commit('change_data', 'titi')
          }
      },
      //最好用computed计算属性, 数据一更改就重新渲染页面
      computed:{
          name:function () {
            return this.$store.state.name
          }
      },
      mounted(){
          this.$axios.request({
            url:'http://127.0.0.1:8000/demo/',
            methods:'get'
          }).then(function (data) {
            console.log(data.data)
          }).catch(function (data) {
            //失败后做的事情
          })
      }


    }
</script>

<style scoped>

</style>

 仓库中的内容;

//store就是需要东西共享给其他组件使用的部分
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);
export default new vuex.Store({
  state:{
    name:'lili'
  },
  //对state中的数据进行二次处理
  //this. $store. geters
  getters:{
    new_name: function (state) {
      return state.name + '美丽'
    },
    new_s:function (state, getters) {
      return getters.new_name + 'yes'
    },

  },
  //接收传来的事件
  mutations:{
    change_data:function (state, data) {
      //自己处理changedata事件
      // 修改data中的数据
      // store中的数据虽然该了, 但是他不会通知组件,
      state.name = data
    }
  }
});

2 axios

  a : 定义基于Promise的HTTP请求客户端,可以同时在浏览器和node.js使用。

  b : 安装和使用:

    安装: npm install axios 

    基本配置:

// main.js
import axios from "axios"

Vue.prototype.$axios = axios

// 组件中
methods: {
     init () {
        this.$axios({
             method: "get",
             url: "/user"
        })
    },
};

    使用:在上一个组件的内容中:

3 将vuex和axios运用到项目中:

第90天的文件夹.

 

猜你喜欢

转载自www.cnblogs.com/gyh412724/p/9966218.html
今日推荐