【问题标题】:VueJS: Setting data initially based on http responseVueJS:最初基于http响应设置数据
【发布时间】:2017-01-25 02:12:42
【问题描述】:

所以我有一个模板 .vue 文件:

<template>
<div id="app">
    <textarea v-model="input" :value="input" @input="update"></textarea>
    <div v-html="compiledMarkdown"></div>
</div>
</template>

<script>
var markdown = require('markdown').markdown;

export default {
    name: 'app',
    data() {
        return {

            input: '# Some default data'
        }
    },
    mounted: function () {
        this.$nextTick(function () {
            this.$http.get(window.location.pathname + '/data').then((response) => {
                this.input = response.body.markdown;
            }) })

    },

    computed: {
        compiledMarkdown: function() {
            this.$http.post(window.location.pathname, {
            "html": markdown.toHTML(this.input)}).then(function() {
            },function() {
            });
            return markdown.toHTML(this.input);
        }
    },
    methods: {
        update: function(e) {
            this.input = e.target.value

        }
    }
}
</script>

在挂载的函数中,我试图将输入设置为等于 HTTP 请求的响应,但是当您查看此文件时,this.input 仍然与最初声明的相同。如何将已编译的Markdown 函数中的this.input 更改为已安装函数中的this.input。我还可以采取哪些其他方法?

【问题讨论】:

    标签: vuejs2 vue.js


    【解决方案1】:

    您不能从computed property 调用异步方法,您可以使用方法或watcherdocs 运行异步代码

    当您想要执行异步或昂贵的操作以响应不断变化的数据时,这非常有用。

    您必须在输入更改时运行相关代码,如下所示:

    var app = new Vue({
      el: '#app',
      data: {
        input: '# Some default data',
        markdown : ''
      },
      methods: {
         fetchSchoolData: function (schoolId) {
            var url = this.buildApiUrl('/api/school-detail?schoolId=' + schoolId);
            this.$http.get(url).then(response => {
                this.schoolsListData = response.data;
            }).catch(function (error) {
                console.log(error);
            });
        }, 
      },
    mounted: function () {
        this.$nextTick(function () {
            this.$http.get(window.location.pathname + '/data').then((response) => {
                this.input = response.body.markdown;
            })
          })
    },
    watch: {
      // whenever input changes, this function will run
      input: function (newInput) {
            this.$http.post(window.location.pathname, {
              "html": markdown.toHTML(this.input)}).then(function() {
            },function() {
              this.markdown = markdown.toHTML(this.input);
            });
      }
    },
    

    看看我的类似回答here

    【讨论】:

    • 手表帮我解决了我的问题,但是这个例子很混乱。
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2017-06-21
    • 2019-01-01
    相关资源
    最近更新 更多