Vuejs v-model special characters

2019-07-17 07:08发布

Can you escape special characters with v-model? I am seeing an issue where I edit text that I receive from a data call. 'this' is showing as '&'#39;this'&#39' in the textarea when editing. I know of v-html, but can you use that with v-model? If not, what is another option?

标签: vue.js vuejs2
2条回答
▲ chillily
2楼-- · 2019-07-17 07:33

v-model works like v-text and shows all characters while v-html let you show the html code. If you see "this" in you source file/debugger/response the reason might be the encoding or that you try to display json-text. Because ' is the NCR dez. for the character ' .

v-model gives automatic two way binding, if you do not need that you can use one of the other directives.

查看更多
smile是对你的礼貌
3楼-- · 2019-07-17 07:38

The issue is that you have encoded text and you need to convert it to plain text. If it is proper HTML, one common trick is to set it as the innerHTML of a scratch div, and then extract the textContent from that div. I've created a little helper function in my snippet below to do that.

The text you give looks like it has some extra quotes in it, so there may be some more massaging of the data that you need to do to unpollute it, but the approach is still what I show here: fetch the text, unpollute it, and assign the unpolluted text to the variable you want to edit.

const scratchDiv = document.createElement('div');
function toPlainText(html) {
  scratchDiv.innerHTML = html;
  return scratchDiv.textContent;
}

new Vue({
  el: '#app',
  data: {
    plainText: ''
  },
  mounted() {
    // fetching code-polluted text
    this.plainText = toPlainText("'this&#39");
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <textarea>
  {{plainText}}
  </textarea>
</div>

查看更多
登录 后发表回答