如何在VueJS中将HTML转换为其他类型?

时间:2018-10-02 21:00:09

标签: vuejs2

我的Messages.vue文件中包含以下内容:

<div class="msg" v-for="(msg, index) in messages" :key="index">
    <p class="msg-index">[{{index}}]</p>
    <p class="msg-subject" v-html="msg.subject"></p>
    <p class="msg-body" v-html="msg.body"></p>
    <input type="submit" @click="deleteMsg(msg.pk)" value="Delete" />
    <input type="submit" @click="EditMsg(msg.pk)" value="Edit" />
</div>
<script>
export default {
  name: "Messages",
  data() {
    return {
      subject: "",
      msgBody: "",
      messages: [],
    };
  },
  mounted() {
    this.fetchMessages();
  },
  ....

我希望msg-subjectmsg-body更改为input HTML元素,以便用户可以编辑并提交它们以进行更新。我不太确定用VueJS实现这种操作的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

<template>
  <div>
      <div class="msg" v-for="msg in messages" :key="msg.id">
          <p class="msg-index">[{{  msg.id }}]</p>
          <p class="msg-subject" v-text="msg.subject" 
            v-show="!msg.editing"></p>
          <input type="text" name="msg-subject"
            v-model="msg.subject" v-show="!!msg.editing">
          <p class="msg-body" v-text="msg.body" 
            v-show="!msg.editing"></p>
          <input type="text" name="msg-body" v-model="msg.body"
            v-show="!!msg.editing">
          <button @click="deleteMsg(msg.id)"> Delete </button>
          <button @click="editMsg(msg.id)"> Edit </button>
      </div>
  </div>
</template>




<script>
... // your usual component code
data(){
    return{
        messages:{
            ...
            editing:false,
                }
        }
    },
methods: {
    EditMsg(id){
    this.editing = true;
    // you can do a direct axios ajax or fetch to edit the updated value
    },
    deleteMsg(id){
    // you can do a direct axios ajax or fetch to delete value
    }

}
... // remaining component code
</script>

旁注:

1 => ,建议不要使用索引作为键,索引有不同的用途,您可以阅读有关使用Index as a key is an anti-pattern here的信息。