1. 程式人生 > 實用技巧 >VUE篇 6 axios vuex 元件引用

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 **

五虎將!:state\mutations\actions\getters\modules\

修改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/>'
})