【问题标题】:Inserting dynamic html tags using Vue.js使用 Vue.js 插入动态 html 标签
【发布时间】:2018-08-25 10:46:46
【问题描述】:

我尝试在写一些消息时动态通知。

这是我的 vue.js 代码。

<script>
Vue.http.options.emulateJSON = true; // Send as 
new Vue({
  el: '#app',
  data: {
      name : "",
      postResult : ""
  },
  methods: {
    click: function() {
      this.$http.post('/api/test',   {name:this.name}).then(function(response){
        var result = response.data;
        //this.postResults.push(result.name);
        if (result.name == "1234")
        {
          this.postResult = "<div> Success </div>";
        } 
        else 
        {
          this.postResult = "<div> Fail </div>";
      }
    }, function(response){
      // Error Handling
    });
  }
}
});
</script>

当我使用jQuery的Ajax时,我使用了这种方法。但是我的 vue.js 脚本不工作。我应该更多地学习 Vue JS 吗?还是我忘记了这个 vue.js 中的一些语法?

【问题讨论】:

  • 你是什么意思“但是我的 vue js 脚本在 vue 中不起作用......”你在 postResult 上看不到成功/失败?
  • @samayo 是的。那是真的。对不起,我使用了错误的语法。
  • 你会用axios吗? vue http 目前有点过时了
  • 对我来说它似乎在工作jsfiddle.net/943bx5px/167 如果你想插入动态 div,请检查这个答案stackoverflow.com/questions/47202998/…
  • 实际上这可能是嵌入html标签jsfiddle.net/943bx5px/170的更简单的解决方案

标签: javascript vue.js


【解决方案1】:
<template>
  <div v-if='requestCompleted'>
    <div v-if='!postResult'> Fail </div>
    <div v-else-if='postResult'> Success </div>
  </div>
</template>

<script>
Vue.http.options.emulateJSON = true; // Send as 
new Vue({
  el: '#app',
  data: {
      name : "",
      postResult : null,
      requestCompleted: false
  },
  methods: {
    click: function() {

      this.$http.post('/api/test',   {name:this.name}).then((response)=>{
        var result = response.data;
        this.requestCompleted=true;
        if (result.name == "1234")
        {
          this.postResult = true;
        } 
        else 
        {
          this.postResult = false;
      }
    }, function(response){
      // Error Handling
    });
  }
}
});
</script>

使用箭头函数在回调函数中访问“this”。

对于 HTTP 请求,最好使用 Axios。此外,您可以使用 vuex 存储并通过操作管理您的请求

【讨论】:

    【解决方案2】:

    您的响应回调中没有“this”。在点击函数的顶层执行var me = this,然后在回调中执行me.postResult = ...。

    一般来说,尝试将所有标记保留在模板元素中,不是吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 2016-10-01
      • 2015-09-16
      • 2019-05-04
      • 2019-02-13
      相关资源
      最近更新 更多