VueJS:最初根据http响应设置数据

时间:2017-01-25 02:12:42

标签: vuejs2 vue.js

所以我有一个模板.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。我可以采取哪些其他方法?

1 个答案:

答案 0 :(得分:1)

您无法从computed property调用异步方法,您可以使用方法或watcher运行异步代码,来自docs

  

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

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

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