javascript - v-model取不到数据?
巴扎黑
巴扎黑 2017-04-11 12:54:51
0
0
842

1.问题

<textarea>里用户输入内容(js代码),会进行实时语法高亮渲染,使用到v-el来获取此元素。

同时<textarea>也在一个表单中会被提交,提交时需要获取<textarea>里面内容,用到v-model:

<textarea v-el:editor v-model="snippet"></textarea>

现在的问题:v-model取不到数据

2.代码

vue-cli webpack模版建立项目。

main.js

import Vue from 'vue'
import App from './App'

/* eslint-disable no-new */
new Vue({
  el: 'body',
  components: { App }
})

index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8"/>
</head>
<body>
  
  <h1>app</h1>
  <app></app>

</html>

App.vue

<template>
  <p id="app">
    <textarea v-model="snippet" v-el:editor></textarea>
    {{snippet}}
    <button v-on:click="runSnippet">运行</button>
  </p>
</template>

<script>
import CodeMirror from './components/v-codemirror/alias'

export default {
  ready () {
    const dom = this.$els.editor
    this.initEditor(dom)
  },
  data () {
    return {
      snippet: ''
    }
  },
  methods: {
    // 初始化编辑器
    initEditor (dom, readOnly) {
      /* eslint-disable */
      const editor = CodeMirror.fromTextArea(dom, {
        lineNumbers: true,
        mode: 'javascript',
        lint: true,
        gutters: ['CodeMirror-lint-markers'],
        readOnly: readOnly ? 'nocursor' : false,
        tabSize: 2,
        styleActiveLine: true
      })
      /* eslint-enable */
    },
    runSnippet () {
      alert(this.snippet)
    }
  }
}
</script>

components/v-mirror/alias.js

import CodeMirror from 'codemirror/lib/codemirror.js'
require('codemirror/lib/codemirror.css')
require('codemirror/addon/lint/lint.css')
require('codemirror/mode/javascript/javascript.js')
require('codemirror/mode/css/css.js')
// require('jsonlint')
require('codemirror/addon/lint/lint.js')
require('codemirror/addon/lint/javascript-lint.js')
// require('codemirror/addon/lint/json-lint.js')
require('codemirror/addon/selection/active-line.js')

export default CodeMirror
巴扎黑
巴扎黑

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template