【问题标题】:Vue.js, Axios, JSon and no refreshVue.js、Axios、JSon 和无刷新
【发布时间】:2017-11-06 21:24:49
【问题描述】:

很抱歉发布它,但我尝试了在网络上找到的所有解决方案。这似乎是一个常见的问题,但我就是无法让它工作。经过一整天的努力,我放弃了。这一定是个傻点,任何vue.js高手都会在几秒钟内找到点。任何帮助将不胜感激。

要点:我收到一些 JSON 并尝试使用收到的值更新我的页面,但字段为空。 jsonSettings.length 始终为 0。

我想我明白为什么:这肯定是因为数组上的“指针”没有改变,所以 vue.js 没有检测到内容的变化,或者类似的东西,但我就是不能让它工作它让我发疯。

我的 HTML:

<!DOCTYPE html>
<html>
<head>
    <title>List</title>
    <script src="/js/vue.min.js"></script>
    <script src="/js/axios.js"></script>
</head>
<body>
    <div id="app">
        Message : {{ message }} <BR>
        Length : {{ jsonSettings.length }} <BR>
        Typeof : {{ jsonSettings.typeof }} <BR>
        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>
    </div>
</body>
<script src="/javascripts/axios.js"></script>
</html>

我的 JavaScript:

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        // jsonSettings: [],
    },
    methods: {
        jsonSettings : function() {
            return (
                [
                    { id: 0, resume: 'test 0'},
                    { id: 1, resume: 'test 1'},
                    { id: 2, resume: 'test 2'}
                ]
            )
        },

        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(function (response) {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                    this.message = "getData - OK";

                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + jsonSettings.length + "]";

            jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})

再次抱歉,但我无法让它工作,因为这个愚蠢的点,我被困在河中间:-(

【问题讨论】:

标签: arrays json binding vue.js axios


【解决方案1】:

不正确的this 再次出现。从本质上讲,axios 回调中的 this 不是对 Vue 的引用。为了使其指向 Vue,您需要使用箭头函数,或使用 bind 或在闭包中捕获正确的 this。在这里,我使用的是箭头函数。

getData : function () {
  axios.get('/axios/LoadAxiosData')
    .then(response => {
      this.jsonSettings = response.data;
      this.message = "getData - I get objects : " + jsonSettings.length + " lines ";

    })
    .catch(error =>  {
        this.message = "getData - I get null";
    });
},

How to access the correct this inside a callback?

同时删除您的 jsonSettings 方法并重新添加 data 属性。

data: {
    message: 'Hello Vue!',
    jsonSettings: [],
},

工作example。您会在示例中看到我清理了其他一些东西。

【讨论】:

  • 谢谢伯特,它正在工作!如果我理解正确,这是一个范围问题(this.jsonSettings in axios get "then" 没有指向 "Vue" jsonSettings),我将调查您提供的其他解决方案,它正在工作,但我不明白为什么(我是一个完整的 javascript 和 vue 初学者)。再次非常感谢伯特
  • @GregoireMulliez 不用担心,对于刚接触 javascript 和 vue 的人来说,这是一个常见的错误。理解this 是更难理解的概念之一。
【解决方案2】:

对于下一个读者,Bert 提供的 => 方法就像一个魅力,案例已关闭。

我在这里发布完整的工作代码以供进一步使用,希望它对您的研究有所帮助。

HTML 代码页:

<!DOCTYPE html>
<html>
<head>
    <title>List</title>
    <script src="/js/vue.min.js"></script>
    <script src="/js/axios.js"></script>
</head>
<body>
    <div id="app">
        Message : {{ message }} <BR>
        Length : {{ jsonSettings.length }} <BR>
        <ul>
            <li v-for="setting in jsonSettings">
                {{ setting.resume }}
            </li>
        </ul>
        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>
    </div>
</body>
<script src="/javascripts/axios.js"></script>
</html>

vue javascript:

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        jsonSettings: []
    },
    methods: {
        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(response => {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + this.jsonSettings.length + "]";
            this.jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})

对于服务器代码 - 不要忘记 npm install --save axios 和 vue 并将这些行添加到您的路由器中:

app.use('/js', express.static(__dirname + '/node_modules/vue/dist')); // redirect Vue.js
app.use('/js', express.static(__dirname + '/node_modules/axios/dist')); // redirect axios.js

我希望能够在没有任何外部链接/库的情况下使用和开发,所以我使用 npm 添加 libs axios、vue(和 boostrap),并使用 express 将链接添加到正确的模块位置

所以服务器代码:

var express = require('express');
var router = express.Router();

// don't forget to change yur dbuser username, password and database name
const sequelize = new Sequelize('postgres://dbuser:password@localhost:5432/database');

const Testing = sequelize.define('testing', {
    resume: Sequelize.TEXT,
    description: Sequelize.TEXT,
    state: Sequelize.BOOLEAN
});

router.get('/', function(req, res, next) {
    res.render('axios', { testings: null });
});

router.get('/LoadAxiosData', function(req, res, next) {
    Testing.findAll({
        order: [ [ 'state' ] ]
    })
        .then (function(testings)   {
            res.json(testings);
        })
        .catch(function(error) {
            console.log("### Error ###" + error);
            res.send(null);
        });
});

// to create database structure - portgresql 
router.get('/init', function (req, res, next) {
    Testing.sync ({force:true});
    res.redirect('/');
});

module.exports = router;

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2020-01-12
    • 2022-11-03
    • 2019-04-11
    • 1970-01-01
    • 2021-04-12
    • 2022-12-19
    • 2022-07-21
    • 2020-08-27
    相关资源
    最近更新 更多