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>
