我正在尝试使用api调用django-rest后端来填充我的数据存储。 api-call看起来运行正常。
加载index.html
后,我可以查看store_.state.products
和v.$store.state.products
,它们似乎都有来自API的json响应。导航到index.html
后,您可以在控制台中看到此处:
和
但是,您可以看到v.$data
似乎是空的。
请在下面找到我的代码。
products.js
//api get call
Vue.use(VueResource)
function get(url, request) {
return Vue.http.get(url, request)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error))
}
//data store
const apiRoot = 'http://127.0.0.1:8000/api/product-list/?format=json'
const store_ = new Vuex.Store({
state: {
products: []
},
mutations: {
'GET_PRODS': function (state, response) {
state.products = response.body;
},
'API_FAIL': function (state, error) {
console.error(error)
},
},
actions: {
getProducts (store) {
return get(apiRoot)
.then((response) => store.commit('GET_PRODS', response))
.catch((error) => store.commit('API_FAIL', error))
}
}
})
//products component
Vue.component('product', {
template: "#product-template",
props: ['product'],
delimiters: ["[[","]]"],
})
//root instance
const v = new Vue({
el: '#app',
store: store_,
data : function () {
return {
//this works fine as expected with hardcoded objects fed as data
//products : [
//{
// id:1,
// name:'test',
// brief:'descrip',
//},
//{
// id:2,
// name:'other',
// brief:'something else',
//}
//]
products : this.$store.state.products
};
},
delimiters: ["[[","]]"],
})
//populate store.state.products with api-call
v.$store.dispatch('getProducts')
的index.html
<!DOCTYPE html>
<html>
<head>
{% load static %}
<link rel="stylesheet" href="{% static '/products/bootstrap.css' %}" />
<link rel="stylesheet" href="{% static '/products/bootstrap-theme.css' %}" />
<link rel="stylesheet" href="{% static '/products/base.css' %}" />
<link rel="stylesheet" href="{% static '/products/index.css' %}" />
<link rel="shortcut icon" href="{% static '/products/favicon.ico' %}"
type="image/x-icon" />
</head>
<body>
<template id="product-template">
<div>
<h1>[[ product.name ]]</h1>
<h5>[[ product.brief ]]</h5>
</div>
</template>
<div id="app">
<div class="container-fluid">
<div class="row title-row">
<h1 class="title">Products</h1>
</div>
<div class="row">
<product v-for="product in products" :product="product" :key="product.id"></product>
</div>
</div>
</div>
<script src="{% static "products/vue.js" %}"></script>
<script src="{% static "products/vue-resource.js" %}"></script>
<script src="{% static "products/vuex.js" %}"></script>
<script src="{% static "products/products.js" %}"></script>
</body>
</html>
答案 0 :(得分:0)
在API填充商店之前,数据中的产品变量可能已初始化。
请尝试使用computed值。计算值随着依赖关系的变化而被动态更新。
//root instance
const v = new Vue({
el: '#app',
store: store_,
computed: {
products: function () {
return this.$store.state.products
}
},
delimiters: ["[[","]]"],
})
但是,您应该使用getter访问商店以确保该属性具有适当的反应性。