VueJS:最初基于http响应设置数据

VueJS: Setting data initially based on http response

所以我有一个模板 .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 仍然与最初声明的相同。如何将 compiledMarkdown 函数中的 this.input 更改为挂载函数中的 this.input 。我还可以采取哪些其他方法?

您不能从 computed property, you can use method or watcher to run asynchronous code, from docs

调用异步方法

This is most useful when you want to perform asynchronous or expensive operations in response to changing data.

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

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);
        });
  }
},

看看我的类似回答