06-vue項目02:vuex、Mutation、Action、ElementUI、axios

 一、Vuex

一、爲何使用VueX

data從最上面的組件,一層層往下傳值,一層層的驗證css

Vue單向數據流html

「中央空調「,代理前端

VueX 解決數據 傳值。。

 

二、Vuex介紹與安裝

(1)Vuex官網

Vuex官網 https://vuex.vuejs.org/zh/installation.htmlvue

   

 

Vue單向數據流jquery

 

  

(2)安裝

VueX安裝:https://vuex.vuejs.org/zh/installation.htmlios

 

三、Vuex的使用

data在store中stateajax

 

 

 

main.js 代碼vuex

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

import router from './router'
Vue.config.productionTip = false

// 1.0 引用vuex
import Vuex from "vuex"
Vue.use(Vuex);

// 1.1 建立sotre
// 若是在模塊化構建系統中,請確保在開頭調用了 Vue.use(Vuex)
const store = new Vuex.Store({
  state: {

    allList:[]  // 後端的數據保存在state中
    // state 這裏面的狀態跟每一個組件的數據屬性有關係

  },
  mutations: {

  }
})


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

四、ajax 獲取後端數據(jquery):跨域問題

(1)下載jQuerydjango

(2)使用jQuery發送ajaxelement-ui

<template>
  <div id="app">
    
    <!-- 2.3 使用Vheader組件 -->
    <Vheader></Vheader>
    
    <router-view/>  <!-- 路由切換 -->
  </div>
</template>

<script>
// 1.0 導入bootstrap
import "bootstrap/dist/css/bootstrap.min.css"

// 2.1 先引入vheader
import Vheader from "./components/Vheader"

// 3.0 引入jQuery
import $ from 'jquery'

export default {
    name: 'App',
    data(){
      return {
        // allList:[] 不會在data存儲太多的數據
      }
    },

    // 2.2 掛載Vheader
    components:{
      Vheader
    },
    created(){

    },
    mounted(){
      
      // 3.1 ajax請求數據
      var _this = this;

      $.ajax({
        url:'http://127.0.0.1:9527/api/v1/comments/',
        methods:"get",
        success:function(data){
          console.log(data)
          console.log(_this)
        
          _this.$store.state.allList = data;
        }

      })
    }
  }
</script>

<style>

</style>

data

 

 (3)vuex: this 如何定位allList

 

(4) 跨域問題  

django後端settings後端設置

 https://www.jianshu.com/p/3961366f9ce9

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'app01',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',  # 注意順序
]
#跨域增長忽略
CORS_ORIGIN_ALLOW_ALL = True #容許全部源訪問(若是不須要容許所有,能夠設置CORS_ORIGIN_WHITELIST=()參數,將須要訪問的域名添加便可)

CORS_ALLOW_CREDENTIALS = True  #是否容許攜帶cookie




CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)


CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)
View Code

 

五、allList of state of store 如何使用?

(1)VnoteList.vue

 

<template>
    <ul>
        <VnoteItem v-for="(item,index) in getAllDatas" :data="item"></VnoteItem>
    </ul>

</template>

<script>
    import VnoteItem from "./VnoteItem"
    export default {
        name:"VnoteList",
        data(){
            return{}
        },
        components:{
            VnoteItem,
        },
        computed:{
            // 監聽
            getAllDatas(){
                return this.$store.state.allList;
        }
    }
    }
</script>

<style scoped>

</style>
View Code

 

 (2)VnoteItem.vue

 ..

<template>
    <li >
        <h2>{{ data.title }}</h2>
        <p>{{ data.content }}</p>
    </li>

</template>

<script>
export default {
    name:"VnoteItem",
    data(){
        return{

        }
    },
    props:{
        // 驗證
        data:Object
    }

}
</script>

<style scoped>

</style>
View Code

 

二、ajax提交數據

post提交一條筆記

一、效果

二、流程如何走

(1)APP.vue + main.js

顯示頁面+控制vuex的store數據

   

 (2)Vnote顯示Vmark組件

三、Vmark組件

<template>
    <div class='wrap'>
    請輸入文字標題: <input type="text" name="" v-model="titleHandler">
    
    <button class="btn btn-success" @click="addOneNote">提交</button>

        <div class="mark">

            <textarea rows="10" cols="100" class='editor' v-model='markdownHandler' ></textarea>

            <div class='show' v-html='currentValue' ref="t"></div>
      
        </div>
    </div>
</template>

<script>

// 導入jQuery
import $ from "jquery"

import Marked from "marked";  
export default {
  name: "Vmark",
  data() {
    return {
      // markValue: ""
    };
  },
  methods: {
    // 添加1條筆記
    addOneNote(){
      console.log(this.$refs.t)
      console.log(this.$refs.t.innerText)

      var json = {
        title:this.titleHandler,  // 1.3 標題添加到json
        markdown:this.markdownHandler,
        content:this.$refs.t.innerText,

      }
      console.log(json);

      // 每次提交刷新數據
      var _this = this;

      // ajax請求 post
      $.ajax({
        url:"http://127.0.0.1:9527/api/v1/comments/",
        method:"post",
        data:json,
        success:function(data){
          console.log(data)
          _this.$store.state.allList = data  // allList筆記列表,更新數據
        },
        error:function(err){
          console.log(err)
        }
      })
    }
  },
  computed: {
    // 1.0 監聽標題
    titleHandler:{
      set:function(newValue){  // 1.2 設置標題的值,給store中的note
        console.log(newValue)
        this.$store.state.note.title = newValue
      },
      get:function(){         //1.1 獲取標題的值
        return this.$store.state.note.title
      }
    },

    // 監聽markdown
    markdownHandler:{
      set:function(newValue){  
        console.log(newValue)
        this.$store.state.note.markdown = newValue
      },
      get:function(){         
        return this.$store.state.note.markdown
      }
    },

    currentValue() {
      return Marked(this.$store.state.note.markdown);
    }
  }
};
</script>

<style>

.mark {
  width: 800px;
  height: 400px;
  margin: 0 auto;
}
.editor,.show {
  float: left;
  width: 395px;
  height: 400px;
  border: 1px solid #666;
}
</style>

(1) Vmark監聽數據

(2)computed計算屬性:$store.state.note

 (3)click提交數據+ajax提交json+刷新數據

(4)markdown格式:獲取一塊標籤 refs.t

 

三、mutations 如何使用(不推薦)

Mutaitons官網 https://vuex.vuejs.org/zh/guide/mutations.html

一、改變store中的store

二、$ajax: get方法 

原冗餘代碼

main.js 聲明回調函數

App.vue 調用 回調函數

三、$ajax:post方法

原冗餘ajax

main.js 聲明回調函數,帶參數

Vmark.vue調用回調函數 ,傳參數

四、Action(推薦)

https://vuex.vuejs.org/zh/guide/actions.html

一、爲何使用Action?異步

 

二、如何使用

ation --->commit觸發---->mutations

 

 dispatch分發Action

 

五、Element

一、介紹

前端UI對比:http://www.javashuo.com/article/p-rivfnwaf-ko.html

ElementUI https://element.eleme.cn/#/zh-CN/component/installation

 

二、使用element

在 main.js 中寫入如下內容:

import Vue from 'vue';
import App from './App.vue';

// 使用element
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);


new Vue({
  el: '#app',
  render: h => h(App)
});

使用btn按鈕

 

三、封裝本身的按鈕(slot)

(1)達到這種效果

 (2)class去計算屬性

 (3)實現

VnoteItem.vue 聲明,引入按鈕

<template>
    <li >
        <h2>{{ data.title }}</h2>
        <p>{{ data.content }}</p>
        <!-- <el-button type="success" round>成功按鈕</el-button> -->
        <VnoteBtn typed='info' >刪除按鈕</VnoteBtn>

    </li>

</template>

<script>
import VnoteBtn from "./VnoteBtn"
export default {
    name:"VnoteItem",
    data(){
        return{

        }
    },
    props:{
        // 驗證
        data:Object
    },
    computed:{

    },
    methods:{
        // var id 

        // dispatch
    },
    components:{
        VnoteBtn
    }

}
</script>

<style scoped>

</style>
View Code

 

 VnoteBtn.vue組件,設計

<template>
    <button class="btn" :class = "currentBtn" >
        <!-- 插槽  分發 -->
        <slot>按鈕</slot>
        
    </button>
</template>


<script>
export default {
    name:"VnoteBtn",
    data(){
        return {

        }
    },
    props:{
        typed:String
    },
    computed:{
        currentBtn(){
            console.log(this.typed)
            return{
                "btn-success": this.typed == "success"? true:false,
                "btn-info": this.typed == "info"? true:false,
            }
        } 
    }

} 
</script>

<style scoped>


</style>
View Code

 

 

四、後續做業

刪除一條數據

點擊一條數據,賦值到markdown

六、axios技術:vue中的ajax

處理請求

以前用jquery的$.ajax

vue也有,axios技術

 axios文檔 https://www.kancloud.cn/yunye/axios/234845

axios中文官網 http://www.axios-js.com/zh-cn/docs/

相關文章
相關標籤/搜索