VUE篇 6 axios vuex 组件引用

router文件夹下的index.js 放路由导航和挂载

     每创建一个组件 就要在index.js 导入啦 设置路由啦

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Course from '@/components/Course'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect:'/Home'

    },
    {
      path: '/',
      name: 'Course',
      component: Course
    },
    {
      path: '/',
      name: 'Home',
      component: Home
    },

  ]
})
index.js

VUE文件格式如下 基本上在编译器中输入vbase 加tab 就出来了

//LuffyContent.vue
<template>
    //当前组件的结构
  <div v-for = 'item in list'>
    //指令系统  数据驱动视图
  </div>
</template>

<script>
   //当前组件的业务逻辑
  export default {
    name:'LuffyContent',//当前组件注册全局组件时,作为 Vue.component()
    data(){
        return {}
    }
  }
</script>

<style scoped>
//当前组件样式
</style>
View Code

axios

相当于jquery ajax

官网:https://www.kancloud.cn/yunye/axios/234845

  

1.下载

npm i axios -S   // npm install --save axios

将axios挂载到vue的原型上,那么在各个组件中都能使用,因为面向对象(继承) 

main.js

import Axios from 'axios'  
Vue.prototype.$Http = Axios   

具体的用法是这样的 (get示例)

   我们想在课程组件中获取课程列表

<template>
<div>
  <div class="catList">
    <span @click="catHandler(index)" v-for="(item,index) in catList" :key="item.id" :class="{active:index==current}">{{item.name}}</span>
  </div>
</div>
</template>

<script>
export default {
name: "Course",
data(){
  return{
    catList:[],
    current:0
  }
}
,
  methods:{
  // 获取分类列表的数据
    catHandler(index){
      this.current = index
    },
    getList(){
      this.$Http.get('https://api.luffycity.com/api/v1/course/category/actual/?courseType=actual&format=json')
      .then(res=>{

        var data = res.data;
        console.log(data);
        if (data.code===0){
          this.catList = data.data;
          let obj = {
            id:0,
            name:'全部',
          }
          this.catList.unshift(obj);
          // 数字
        } else {
          //
   }

      }).catch((err)=>{
        console.log(err);
      })
    }
  },
  created() {
  this.getList()
  }
}
</script>

<style scoped>
span {
  padding: 0 20px;
}
 span.active {
    color: aqua;
 }
</style>
View Code

上面有鼠标点击span 变色的示例

有v-for 绑定 key的示例 (顺序不会乱)

有unshift在头部插值的示例

新增一个在数组中任意地方插入值的方法,

    我们知道splice可以删除任意索引开始的任意个值,如arr.splice(1,2)  删除索引1开始的2个值

    那么 splice(0,0)代表不删除吧

      所以 arr.splice(0,0,'z','x','d')  代表在数组最前面增加3个值 为'z','x','d'

      当然其他位置也行  第二个位置参数为零就行

设置全局的默认前缀地址

main.js

axios.defaults.baseURL = 'https://api.luffycity.com/api/v1/';
<template>
<div>
  <div class="catList">
    <span @click="catHandler(index,item.id)" v-for="(item,index) in catList" :key="item.id" :class="{active:index==current}">{{item.name}}</span>
  </div>
  <div class="course">
    <ul>
      <li v-for="(course,index) in courseList" :key="course.id">
      <h3> {{course.name}}</h3>
      </li>
    </ul>
  </div>
</div>
</template>

<script>
export default {
name: "Course",
data(){
  return{
    catList:[], //分类列表
    current:0,
    courseList:[],  //课程列表
    catId:0,
    xx:'',
  }
}
,
  methods:{
  getCourseList(){
    if (this.catId!==0){
      this.xx ='actual/?category_id='+ this.catId;
    }else {
      this.xx ='actual/'
    }
      this.$Http.get(this.xx)
    .then((res)=>{
      var data = res.data;
      this.courseList = data.data;
      console.log(this.courseList);
    })
  }
,
  // 获取分类列表的数据
    catHandler(index,catId){
      this.current = index;
      this.catId = catId;
      this.getCourseList();
    },
    getList(){
      this.$Http.get('category/actual/?courseType=actual&format=json')
      .then(res=>{

        var data = res.data;
        console.log(data);
        if (data.code===0){
          this.catList = data.data;
          let obj = {
            id:0,
            name:'全部',
          }
          this.catList.unshift(obj);
          // 数字
        } else {
          //
   }

      }).catch((err)=>{
        console.log(err);
      })
    }
  },
  created() {
  this.getList(),
    this.getCourseList()
  }
}
</script>

<style scoped>
span {
  padding: 0 20px;
}
 span.active {
    color: aqua;
 }
</style>
Course.vue
// 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 Axios from 'axios'
Vue.prototype.$Http = Axios


Vue.config.productionTip = false
Axios.defaults.baseURL = 'https://api.luffycity.com/api/v1/course/';
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
main.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Course from '@/components/Course'

import Axios from 'axios'



Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect:'/helloWorld',

    },
    {
      path: '/helloWorld',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/Course',
      name: 'Course',
      component: Course
    }
  ]
})
index.js

看看组件的引用挂载呀

  子组件

View Code

在Home组件中使用他

<template>
<div> 我是首页


<-- 使用--> <Son></Son> </div> </template> <script> import Son from './Son' //导入 export default { name: "Home", components:{ // 挂载 Son } } </script> <style scoped> </style>

全局引用挂载呢?

main.js

import Home from "./components/Home";
vue.component(Home.name,Home)

然后在其他组件不需要导入了

直接用<Home></Home>

 还有一种方法:

vuex **

  五虎将!:statemutationsactionsgettersmodules

修改state的唯一方法是提交:   

actions 异步

mutations 同步

 

1.下载npm i vuex -S

2 在main.js使用

main.js


import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state:{ num:1 //数据 }, mutations:{ //同步方法 通过组件中的commit传到这里 }, actions:{ //异步方法 传到mutations中 } })

//记得要在Vue中挂载他

3、在组件中通过computed检测他,并在模板中使用他使用

  computed:{
    myNum:function (){
      return this.$store.state.num
    }
  }


<h1>我是父组件中的{{myNum}}</h1>

传递同步/异步 方法的时候如下

<template>
<div>
<h2>我是子组件{{mySonNum}}</h2>
  <button @click="addNum">同步commit到mutations</button>
  <button @click="addAsyncNum">异步</button>

</div>
</template>

<script>
export default {
name: "Son",
  methods:{
    addNum(){
      //不要直接修改 state中的状态
      //commit 触发 这个事件  同步
      // this.$store.commit('setNum',1)
      this.$store.dispatch('setActionNum',1)
    },
    addAsyncNum(){
      this.$store.dispatch('setActionAsync',5)
    }
},
  computed:{
  mySonNum:function (){
    return this.$store.state.num
  }
  }
}
</script>

<style scoped>

</style>
Son.vue
// 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 Axios from 'axios'


Vue.prototype.$Http = Axios


Vue.config.productionTip = false
Axios.defaults.baseURL = 'https://api.luffycity.com/api/v1/course/';

import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state:{
    num:1
  },
  mutations:{
    setMutaNum(state,val){
      console.log(val)
      state.num+=val
    },
    setMutaAsync:function(state,val){
      state.num+=val

    },
    course_questions(state,data){
      state.questionList = data;

    }
  },
  actions:{
    setActionNum(context,val){
      //Action 提交的是 mutation,而不是直接变更状态。
      context.commit('setMutaNum',val)
    },
    setActionAsync:function(context,val){
      setTimeout(()=>{
        context.commit('setMutaAsync',val)
      },1)

    },
    course_questions(context,courseId){
      //异步  aixos 异步
      Axios.get(`course_questions/?course_id=${courseId}`)
        .then((res)=>{
          console.log(res)
          let data = res.data.data;
          context.commit('course_questions',data)
        })
        .catch((err)=>{
          console.log(err)
        })
    }
  }

})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
main.js

很明显 组件如果要修改状态 需要先dispatch 异步 在commit 同步修改状态,最后返回给组件(因为我们从后端获取数据都是异步的 例如ajax)

vuex的action中请求ajax 

<template>
  <div>
<!--    <p v-for = '(question) in questionList ' :key='question.id'>{{question.answer}}</p>-->
    <p>{{questionList}}</p>
  </div>
</template>

<script>
export default {
  name:"CourseDetail",
  created(){
    // console.log(this.$route.params.courseId)
    this.$store.dispatch('course_questions',this.$route.params.courseId)
  },
  computed:{
    questionList(){
      return this.$store.state.questionList
    }
  }
}
</script>

<style scoped>

</style>
detail.vue
// 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 Axios from 'axios'


Vue.prototype.$Http = Axios


Vue.config.productionTip = false
Axios.defaults.baseURL = 'https://api.luffycity.com/api/v1/course/';

import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state:{
    num:1,
    questionList:{}
  },
  mutations:{
    setMutaNum(state,val){
      console.log(val)
      state.num+=val
    },
    setMutaAsync:function(state,val){
      state.num+=val

    },
    course_questions(state,data){
      state.questionList = data;

    }
  },
  actions:{
    setActionNum(context,val){
      //Action 提交的是 mutation,而不是直接变更状态。
      context.commit('setMutaNum',val)
    },
    setActionAsync:function(context,val){
      setTimeout(()=>{
        context.commit('setMutaAsync',val)
      },1)

    },
    course_questions(context,courseId){
      //异步  aixos 异步
      Axios.get(`actual/${courseId}/payment/?courseType=actual&id=${courseId}`)
        .then((res)=>{
          console.log(res)
          let data = res.data.data;
          context.commit('course_questions',data)
        })
        .catch((err)=>{
          console.log(err)
        })
    }
  }

})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
main.js
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state:{
    num:1,
    questionList:[]
  },
  mutations:{
    setMutaNum(state,val){
      console.log(val)
      state.num+=val
    },
    setMutaAsync:function(state,val){
     state.num+=val
    
    },
    course_questions(state,data){
      state.questionList = data;
     
    }
  },
  actions:{
    setActionNum(context,val){
      //Action 提交的是 mutation,而不是直接变更状态。
      context.commit('setMutaNum',val)
    },
    setActionAsync:function(context,val){
      setTimeout(()=>{
        context.commit('setMutaAsync',val)
      },1)
     
     },
     course_questions(context,courseId){
       //异步  aixos 异步
       Axios.get(`course_questions/?course_id=${courseId}`)
       .then((res)=>{
        console.log(res)
        let data = res.data.data;
        context.commit('course_questions',data)
       })
       .catch((err)=>{
        console.log(err)
       })
     }
  }
})

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
原文地址:https://www.cnblogs.com/zhuangdd/p/13779772.html