【问题标题】:Use VueJs to save a template使用 VueJs 保存模板
【发布时间】:2018-02-03 16:04:59
【问题描述】:

我的项目目前是用 VueJS 制作的。现在,我们需要使用输入数据处理某个模板,然后存储结果并使用它来发送电子邮件(例如)。

我可以使用用户数据渲染模板并保存吗?怎么样?

我不想为此使用其他库,除非我们不能使用 VueJS

我已阅读有关 SSR 的信息。但我不想使用服务器端渲染。这个想法只是呈现某些消息。遵循这样的行为:

save: function(){
    userNote.user = ...
    userNote.message = document.getElementById('message').innerHtml;
    saveToServer(userNote);
}

消息模板:

<div id="message"> Dear {{user.name}}, please confirm that {{notes}} before {{date}}</div>

我希望我能理解。 提前致谢。

【问题讨论】:

标签: static vue.js vuejs2 vue-component


【解决方案1】:

假设您的模板存储在一个组件中,您可以添加一个导出方法:

var templateComponent = Vue.component("template-component", {
  template: "<p>Hello {{name}}</p>",
  props: ["name"],
  methods: {
    exportHTML: function() {
      return this.$el.outerHTML;
    }
  }
});

var app = new Vue({
  el: '#app',
  data: {
    name: "David",
    html: undefined
  },
  methods: {
    getHTML: function() {
      this.html = this.$refs.template.exportHTML();
    }
  }
});
<script src="https://unpkg.com/vue@2.4.2/dist/vue.min.js"></script>
<div id="app">
    <div style="display: none">
        <template-component :name="name" ref="template"></template-component>
    </div>

    <label>Name
        <input v-model="name">
    </label>

    <button @click="getHTML">Get html</button>

    <pre>{{ html }}</pre>
</div>

然后你只需要调用模板组件上的 exportHTML 方法来检索 HTML。

【讨论】:

  • 这在这个例子中有效。我需要知道子元素的位置。如果我添加其他孩子,我可能会小心我把它放在哪里。
  • 我稍微编辑了我的答案,以便以更好的方式访问模板。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 2016-04-22
  • 2016-11-14
  • 2017-02-09
  • 2019-05-25
  • 1970-01-01
相关资源
最近更新 更多